0

I cannot find out the regex to get param value from the part of query string:

I need to send parameter name to a method and get parameter value as result for string like "p=1&qp=10". I came up with the following:

function getParamValue(name) {

  var regex_str = "[&]" + name + "=([^&]*)";

  var regex = new RegExp(regex_str);

  var results = regex.exec(my_query_string);
  // check if result found and return results[1]

}

My regex_str now doesn't work if name = 'p'. if I change regex_str to

var regex_str = name + "=([^&]*)";

it can return value of param 'qp' for param name = 'p'

Can you help me with regex to search the beginning of param name from right after '&' OR from the beginning of a string?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
make_sense
  • 464
  • 4
  • 14
  • possible duplicate of [Use the get parameter of the url in javascript](http://stackoverflow.com/questions/827368/use-the-get-parameter-of-the-url-in-javascript) and [many other questions](http://stackoverflow.com/search?q=javascript+get+parameter+from+query). – Felix Kling May 10 '12 at 15:28

3 Answers3

1

Looks like split will work better here:

var paramsMap = {};
var params = string.split("&");
for (var i = 0; i < params.length; ++i) {
    var keyValue = params[i].split("=", 2);
    paramsMap[keyValue[0]] = keyValue[1];
}

If you desperately want to use a regex, you need to use the g flag and the exec method. Something along the lines of

var regex = /([^=]+)=([^&]+)&?/g;
var paramsMap = {};
while (true) {
    var match = regex.exec(input);
    if (!match)
        break;
    paramsMap[match[1]] = match[2];
}

Please note that since the regex object becomes stateful, you either need to reset its lastIndex property before running another extraction loop or use a new RegExp instance.

Alexander Pavlov
  • 31,598
  • 5
  • 67
  • 93
1

Change your regex string to the following:

//pass the query string and the name of the parameter's value you want to retrieve
function getParamValue(my_query_string , name)
{
    var regex_str = "(?:^|\&)" + name + "\=([^&]*)";
    var regex = new RegExp(regex_str);
    var results = regex.exec(my_query_string); 
    try
    {
        if(results[1] != '')
        {
            return results[1];
        }
    }
    catch(err){};
    return false;
}
Osmaan Shah
  • 345
  • 2
  • 8
  • `[\?\&]?` will be ignored, allowing name to be preceeded with anything. `\=(((?!\&).)*)` is equivalent to and more efficient as `([^&]*)` –  May 10 '12 at 16:13
1

This might work, depending on if you have separated the parameter part.

var regex_str = "(?:^|\&)" + name + "=([^&]*)";
or
var regex_str = "(?:\&|\?)" + name + "=([^&]*)";