Often I have the need to parse the URL query to retrieve the value of a specific named argument. There is no direct way of doing this is JavaScript, so this requires a custom function.
function findQueryArgument (strQuery, strArgumentName) { // Valid query? if (strQuery) { // Split the parameteres var arrParameters = strQuery.split("&"); // Walk through the parameters for (var i = 0; i < arrParameters.length; i++) { // Get the key/value pair var arrPair = arrParameters[i].split("="); // Is this the event argument? if (arrPair[0] == strArgumentName) { // Has value? if (arrPair.length > 1) { // Get the value return arrPair[1]; } // Not set break; } } } // Not found return ''; }
The strQuery argument is the full URL query i.e. a=val1&b=val2 etc. The full URL should not be included.
strArgumentName is the name of the argument you’re looking for, i.e. a or b.
Please notice that the returned value is URL encoded. To extract the actual string value you need to use the built in JavaScript method called unescape.
Here is an example:
// Query string var strQuery = 'a=val1&b=val2'; // Get the value of the 'b' argument var strEscaped = findQueryArgument(findQueryArgument, strQuery, 'b'); // Get the unescaped value var strUnescaped = unescape(strEscaped); // Display the value alert(strUnescaped);