-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;
}
NJD
  • 1
  • 3

2 Answers2

2

Simple question: what variables do you expect from this?

a=b&c&d=e

Is it ?

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

So there is an ambiguity, and your problem can't be resolved, if you don't have the set of names.

UPDATE: If query string contains only name=value pairs,and there are no single name parameters, then you can extract those pairs by below script:

 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"}
Engineer
  • 47,849
  • 12
  • 88
  • 91
1

& is a special character which purpose is to break the url into multiple variables. If it is a value, it is encoded.

Also, I'd look at this answer for a complete function to handle parameters: How can I get query string values in JavaScript?

Community
  • 1
  • 1
Florian Margaine
  • 58,730
  • 15
  • 91
  • 116