"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > 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?

Published on 2024-11-11
Browse:684

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:

function getQueryParam(name) {
  const regex = new RegExp('[?&]'   encodeURIComponent(name)   '=([^&]*)');
  const result = regex.exec(location.search);
  return result ? decodeURIComponent(result[1]) : undefined;
}

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:

const foo = getQueryParam('foo');

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

Release Statement This article is reprinted at: 1729248736 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3