如何从URL中获取参数是一个很基本的问题。首先假定URL是合法的,code 如下,欢迎各位大大code review.
1. 可以使用一个match和循环split
function findQueriesFromUrl(url){ var regex, matches, i, length, pair, result = {}, query; if(!url) return; regex = /\w+\=\w*/g; matches = url.match(regex); for(i = 0, length = matches.length;i<length;i++){ pair = matches[i].split('='); result[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]); } return result; }
2. 可以使用exec获得所有的分组,
function findQueriesFromUrl(url){ var regex, result = {}, match; if(!url) return; regex = /(\w+)\=(\w*)/g; //没有/g会死循环。 while(match = regex.exec(url)){
result[decodeURIComponent(match[1])] = decodeURIComponent(match[2]); } return result; }
需要注意的是,exec只有针对同样的调用对象和同一个字符串的引用作为参数的时候才能迭代返回所有的分组,否则可能会死循环, 例如如下的代码就会死循环:
while(match = (/(\w+)\=(\w*)/g).exec(url)){ result[match[1]] = match[2]; }
题外话,exec函数会循环返回所有match的对象,例如调用
(function excute(url){ var regex, result = {}, match, i = 0; regex = /(\w+)\=(\w*)/g; while(i < 10){ i++; console.log(regex.exec(url)); } return result; })('a=b');
会循环输出一个match的对象和null, 如下:
["a=b", "a", "b", index: 0, input: "a=b"] null ["a=b", "a", "b", index: 0, input: "a=b"] null ["a=b", "a", "b", index: 0, input: "a=b"] null ["a=b", "a", "b", index: 0, input: "a=b"] null ["a=b", "a", "b", index: 0, input: "a=b"] null
如果去掉正则表达式里面的g,输出会变成:
["a=b", "a", "b", index: 0, input: "a=b"] ["a=b", "a", "b", index: 0, input: "a=b"] ["a=b", "a", "b", index: 0, input: "a=b"] ["a=b", "a", "b", index: 0, input: "a=b"] ["a=b", "a", "b", index: 0, input: "a=b"] ["a=b", "a", "b", index: 0, input: "a=b"] ["a=b", "a", "b", index: 0, input: "a=b"] ["a=b", "a", "b", index: 0, input: "a=b"] ["a=b", "a", "b", index: 0, input: "a=b"] ["a=b", "a", "b", index: 0, input: "a=b"]
这样就不能取到所有的匹配了。