码迷,mamicode.com
首页 > 编程语言 > 详细

JavaScript从URL里面获取参数

时间:2014-10-24 23:34:25      阅读:240      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   ar   使用   java   for   strong   

如何从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"] 

这样就不能取到所有的匹配了。

JavaScript从URL里面获取参数

标签:style   blog   color   io   ar   使用   java   for   strong   

原文地址:http://www.cnblogs.com/rixin/p/4049216.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!