-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?

1

2 Answers 2

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.

0
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"]);
1
  • very nice piece of code, I'm still trying to fully grasp that regular expression though... Commented Aug 10, 2012 at 14:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.