将http: //www.a.com/admin/index.php#route=main/nav&user=tom&id=123/profile
后的参数转换成:
[ {"router":"main"}, { "nav":"", "user":"tom", "id":"123" }, {"profile":""} ]
除了循环变量有没有更简洁的方法
拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...
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);
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);
坐等更好方案:
'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: '' }
坐等更好方案: