-1

I'm trying to come out with a regulat expression to extract the value of a querystring parameter

so far now I came with the following:

app.getValue = function() {
  var regExp = '[&?]'+$("#token").val()+'=(.*?)[&$]';
  var re = new RegExp(regExp);
  var res = re.exec($("#url").val());
  if (!res) return '';
  return res[1] || '';
}

the problem seems to be that the "$" in the end of the resultar expression is being interepreted as a literal character, and not as the end of the input string

so with the followgin querystring:

http://wines?len=10&page=500&filter=bogota and salvador&sort=name asc

looking for the token "sort" doesn't get me anything, if I add a "&" or a "$" at the end of the string it works...

Am I missing something?

opensas
  • 60,462
  • 79
  • 252
  • 386
  • possible duplicate of [JavaScript query string](http://stackoverflow.com/questions/647259/javascript-query-string) – katspaugh Aug 09 '12 at 05:51

2 Answers2

1

I looks like it is not possible to express an end-of-line character inside of a character class group. Instead, I think you can just use (&|$|,) to match a comma, ampersand, or end-of-line. Note that this creates a new match group, but that shouldn't affect your code.

apsillers
  • 112,806
  • 17
  • 235
  • 239
1

Try this

var urlParams = {};
(function () {
    var match,
        pl     = /\+/g,  // Regex for replacing addition symbol with a space
        search = /([^&=]+)=?([^&]*)/g,
        decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
        query  = window.location.search.substring(1);

    while (match = search.exec(query))
       urlParams[decode(match[1])] = decode(match[2]);
})();

example:

?var1=test1&var2=test2

result:

alert(urlParams["var1"]);
gaurang171
  • 9,032
  • 4
  • 28
  • 30