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?

1

3 Answers 3

1

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

var regex_str = "(?:^|\&)" + name + "=([^&]*)";
or
var regex_str = "(?:\&|\?)" + name + "=([^&]*)";
Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

I agree but I am also interested in the solution for educational reason :)
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;
}

1 Comment

[\?\&]? will be ignored, allowing name to be preceeded with anything. \=(((?!\&).)*) is equivalent to and more efficient as ([^&]*)

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.