The following Javascript method takes a query parameter and the URL it belongs too, and it returns the value associated with that query parameter.
function getQueryStringValue(param, url) {
if (!url) {
// handle null or undefined
return null;
}
var regex = new RegExp("[?&]" + param + "(=([^&#]*)|&|#|$)");
var results = regex.exec(url);
if (!results) {
// if no match then the param passed in doesn't exist in the query,
// so return null
return null;
}
// If the match succeeds, the exec() method returns an array that
// has the matched text as the first item (0), and then one item
// for each capturing parenthesis (1 and 2) that matched, containing
// the text that was captured. In this case we are looking for the
// text captured in the second capturing parenthesis (2)
var value = results[2];
if (!value) {
// the param exist within the query but it has no value,
// so return an empty string
return '';
}
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
var url = 'www.myapp.com/users/?firstName=Bob&lastName=Smith&age=35';
var lastName = getQueryStringValue('lastName', url); // Smith