Home  >  Article  >  Web Front-end  >  How to Access GET Request Parameters in JavaScript Using Native APIs and Legacy Techniques?

How to Access GET Request Parameters in JavaScript Using Native APIs and Legacy Techniques?

DDD
DDDOriginal
2024-10-18 18:54:03461browse

How to Access GET Request Parameters in JavaScript Using Native APIs and Legacy Techniques?

Accessing GET Request Parameters in JavaScript

Modern browsers provide native APIs for manipulating URLs and query strings. These APIs, including URL and URLSearchParams, should be prioritized for compatibility with modern browsers.

Original Solution:

Prior to native APIs, all GET request parameters were accessible through the window.location.search property. However, this requires manual parsing of the query string. The following function can be used:

<code class="js">function getQueryParam(name) {
  const regex = new RegExp('[?&]' + encodeURIComponent(name) + '=([^&]*)');
  const result = regex.exec(location.search);
  return result ? decodeURIComponent(result[1]) : undefined;
}</code>

This function takes a GET parameter name and returns its value. If the parameter does not exist or has no value, it returns undefined.

Example:

<code class="js">const foo = getQueryParam('foo');</code>

This will assign the value of the GET parameter foo to the foo variable.

The above is the detailed content of How to Access GET Request Parameters in JavaScript Using Native APIs and Legacy Techniques?. 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