Home >Web Front-end >JS Tutorial >How Can I Easily Extract Key-Value Pairs from a JavaScript Query String?

How Can I Easily Extract Key-Value Pairs from a JavaScript Query String?

DDD
DDDOriginal
2024-11-27 08:26:13837browse

How Can I Easily Extract Key-Value Pairs from a JavaScript Query String?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn