Maison > Questions et réponses > le corps du texte
将http: //www.a.com/admin/index.php#route=main/nav&user=tom&id=123/profile
后的参数转换成:
[ {"router":"main"}, { "nav":"", "user":"tom", "id":"123" }, {"profile":""} ]
除了循环变量有没有更简洁的方法
三叔2016-11-10 15:48:59
var url = 'http: //www.a.com/admin/index.php?route=main/nav=&user=tom&id=123/profile', result = []; url.substring(url.indexOf('?') + 1) .replace(/[^\/]+/g, function(objstr) { var obj = {}, empty = false; objstr.replace(/([^\/&=]+)(=([^\/&=]+)?)?/g, function(s, a, b, c) { if(a && b && c){ obj[a] = c; }else if(a && !c){ obj[a] = ''; }else{ empty = true; } }); if(!empty){ result.push(obj); } }); console.log(result);
欧阳克2016-11-10 15:48:41
var url = location.search.substr(1); param = {}; console.log(url); url.replace(/([^?&]+)=([^?&]+)/g, function(s, v, k) { param[v] = decodeURIComponent(k); return k + '=' + v; }); console.log(param);
三叔2016-11-10 15:48:27
坐等更好方案:
'use strict'; var url = 'http: //www.a.com/index.php?route=main&nav&user=tom&id=123&profile'; var querys = url .substring(url.indexOf('?') + 1) .split('&') .map((query) => query.split('=')) .reduce((params, pairs) => (params[pairs[0]] = pairs[1] || '', params), {}); console.log(querys); //{ route: 'main', nav: '', user: 'tom', id: '123', profile: '' }