如何使用正则表达式精美地剖析网址

时间:2014-04-11 16:51:33

标签: regex url

我想使用正则表达式从params赋予url

获取arrayLike对象

e.g。

http://mysite/myPeople?one=jose&two=emily&three=john

基本上它的作用是

    function interpretUrl(url){

        var reg = /\?([^&?=]*)=([^&?=]*)/g; //what am i doing wrong?

        //some logic here
        reg.exec(url)

        return {
            param: [
                one: 'jose',
                two: 'emily',
                three: 'john'
            ],
            root:
        }
    }

1 个答案:

答案 0 :(得分:1)

您可以使用它来从查询字符串中获取所有参数:

var re = /([^?&]+)=([^&]*)/g,
    matches = {},
    input = "http://mysite/myPeople?one=jose&two=emily&three=john";
while (match = re.exec(input.substr(input.indexOf('?')+1))) matches[match[1]] = match[2];

console.log(matches);
//=> {one: "jose", two: "emily", three: "john"}