Home > Web Front-end > JS Tutorial > 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
Release: 2024-10-18 18:54:03
Original
555 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template