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!