Summary:
With this RegEx you can extract the value of a URL GET parameter.
Note: This code is used to explain the concept. It works perfectly fine. A refined code respecting URL encoded
values is
at the bottom of page.
function getQueryParam(param) {
var rx = new RegExp("[?&]" + param + "=([^&]+).*$");
var returnVal = window.location.search.match(rx);
return returnVal === null ? "" : returnVal[1];
}
function getQueryParam(param) {
// ...
}
Obviously we want to be able to extract any parameter. We can call this function for every param that we want to extract its value from the URL. Like so:
// wanting to get the parameter "myParam":
getQueryParam("myParam");
var rx = new RegExp("[?&]" + param + "=([^&]+).*$");
new RegExp
" to define the regular expression. This gives us the
possibility to
dynamically insert the "param" every time. We do so by concatenating the strings with the "+".[?&]
"([^&]+)
" to match one ore more characters not being "&" to get
our return
value. This way this group will contain all characters that are not "&". It will match up to the next "&"
or the end of the URL query string. The "+" quantifier causes this group to only be a match if there
is one or more characters in this group.([^&]+)
" with the "+" the entire RegEx will only match if this
group
holds at least one character. So a query like "?pants=&otherParam=value
" will cause the entire
RegEx to not match and return an empty
string "" for the param "pants" (which is
correct). Same for this query string: "?pants&otherParam=val
".
.*$
". We could
omit this and our RegEx would still work fine since we are not extracting any of this match. However, I always
like
formulating RegExes to their expected end to have clearer speaking code.var match = window.location.search.match(rx);
return returnVal === null ? "" : returnVal[1];
We apply the regular expression to the URL query string by means of the .match()
method. The second line
checks if the RegEx did match at all (if not returnVal
will
be "null").
If
we have no match we return an empty string. If we have a match then we return that.
function getQueryParam(param) {
var rx = new RegExp("[?&]" + param + "=([^&]+).*$");
var returnVal = window.location.search.match(rx);
return returnVal === null ? "" : decodeURIComponent(returnVal[1].replace(/\+/g, " "));
}
This is an extension of the above code. Besides the description above this code also accounts for encoded URL parameter values: In case the value of the param we are looking for has been URL encoded we decode it before returning. Spaces decoded as "+" are changed into spaces again.
get cookie value (very similar case)
Different ways of declaring RegExes
Escaping in regular expressions