Extracting GET Parameters Using JavaScript
When working with web applications, accessing data passed through GET parameters is crucial. This becomes particularly relevant in situations like URL query strings. This article explores various techniques to retrieve GET parameters from JavaScript, providing both simple and more advanced solutions.
Using the window.location Object
One straightforward approach involves utilizing the window.location object. This object contains a search property, which stores the portion of the URL following the question mark. To extract the GET parameters, simply remove the question mark and any leading whitespace:
window.location.search.substr(1)
Using this method, in the example provided of "http://example.com/page.html?returnurl=/admin", the result would be "returnurl=/admin".
Custom Function for Parameter Retrieval
An alternative approach is to create a custom JavaScript function for parameter retrieval. This function can simplify the parameter extraction process:
function findGetParameter(parameterName) { var result = null, tmp = []; location.search .substr(1) .split("&") .forEach(function (item) { tmp = item.split("="); if (tmp[0] === parameterName) result = decodeURIComponent(tmp[1]); }); return result; }
In this example, the findGetParameter() function accepts a parameterName and iterates through the query string, searching for a match. Once a match is found, the corresponding parameter value is returned.
Plain JavaScript for Loops
For even broader compatibility, including Internet Explorer 8, a plain JavaScript for loop can be employed:
function findGetParameter(parameterName) { var result = null, tmp = []; var items = location.search.substr(1).split("&"); for (var index = 0; index < items.length; index++) { tmp = items[index].split("="); if (tmp[0] === parameterName) result = decodeURIComponent(tmp[1]); } return result; }
This solution ensures compatibility with older browsers while maintaining the same parameter retrieval functionality.
The above is the detailed content of How Can I Extract GET Parameters in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!