JavaScript Query Strings
A common technique used in web development is to pass data through a query string. This is often encountered in ASP.NET, where it is represented as a dictionary structure. Many developers may seek a similar solution in JavaScript.
Extracting Key-Value Pairs
To achieve this, one can utilize the location.search property, which captures the portion of the URL following the question mark (?). Within this property lies key-value pairs.
Custom Function
If there is no pre-built JavaScript library specifically designed for this purpose, a custom function can be created:
function getQueryString() { var result = {}, queryString = location.search.slice(1), re = /([^&;=]+)=([^&;]*)/g, m; while (m = re.exec(queryString)) { result[decodeURIComponent(m[1])] = decodeURIComponent(m[2]); } return result; }
With this function, you can easily access query string parameters by calling:
var myParam = getQueryString()["myParam"];
Naming Conventions
Outside of ASP.NET, the term "query string" is more commonly used for the entire string of key-value pairs following the question mark. The individual key-value pairs are referred to as parameters, arguments, or query string parameters.
Browser Implementation
Unfortunately, the location.search property does not natively provide a key-value collection or a structured object representation of the query string. This is why developers often resort to custom functions or external libraries.
The above is the detailed content of How Can I Easily Extract Key-Value Pairs from a JavaScript Query String?. For more information, please follow other related articles on the PHP Chinese website!