-1

How can a JavaScript regular expression be written to separate a URI into query string variables, where the variables itself might contain the '&' character?

I'm currently using the following code- but if any of the variables contain an & embedded it won't capture the rest of that variable. How can this be alleviated?

function uriParameters() {
  var vars = {};
  var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
    vars[key] = value;
  });
  return vars;
}
4

2 回答 2

2

简单的问题:您对此有何期望?

a=b&c&d=e

是吗 ?

a=b&c, d=e     //or 
a=b  , c , d=e

因此,如果您没有名称集,则存在歧义,并且您的问题无法解决。

更新:如果查询字符串只包含name=value对,并且没有单个name参数,那么您可以通过以下脚本提取这些对:

 function getUriParameters( uri ){
     //Some sequence of chars that can't be matched in query string
     var SYN = ",,,";
     var vars = {};
     uri.split("=")
        .map(function(value){    //Replacing last '&' by SYN value
            return value.replace(/&([^&]*)$/,SYN+'$1');
        })
        .join("=")               //Restoring uri
        .split(SYN)              //
        .forEach(function(v){    //Storing 'key=value' pairs
             vars[v.split('=')[0]] = v.split('=')[1];
             //       key                 value
        });
     return vars;
 }
 //Usage-> getUriParameters("a=b&c&d=e")
 //Sample
 console.log( JSON.stringify(getUriParameters("a=b&c&d=e")) );
 //output -> {"a":"b&c","d":"e"}
于 2012-07-03T06:37:37.920 回答
1

&是一个特殊字符,其目的是将 url 分解为多个变量。如果它是一个值,它会被编码。

另外,我会查看这个答案以获得处理参数的完整函数:How can I get query string values in JavaScript?

于 2012-07-03T06:38:17.630 回答