make_sense
make_sense

Reputation: 464

Looking for a regex to parse parameters string for JS

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?

Upvotes: 0

Views: 301

Answers (3)

Osmaan Shah
Osmaan Shah

Reputation: 345

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;
}

Upvotes: 1

user557597
user557597

Reputation:

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

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

Upvotes: 1

Alexander Pavlov
Alexander Pavlov

Reputation: 32286

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.

Upvotes: 1

Related Questions