PASSWORD RESET

Your destination for complete Tech news

How to get query string values in javascript?

453 0
< 1 min read

To get query string values in JavaScript, you can use the URLSearchParams object of the URL object. The URLSearchParams object allows you to parse and access the query string of a URL, and it provides several methods for retrieving and manipulating the query string parameters.

Here is an example of how to use the URLSearchParams object to get the value of a specific query string parameter:

// Get the current URL
let url = new URL(window.location.href);

// Get the value of the "id" query string parameter
let id = url.searchParams.get('id');

console.log(id);  // Outputs the value of the "id" parameter

You can also use the getAll method to get an array of all the values for a specific query string parameter:

// Get the current URL
let url = new URL(window.location.href);

// Get an array of all the values for the "color" parameter
let colors = url.searchParams.getAll('color');

console.log(colors);  // Outputs an array of all the values for the "color" parameter

The URLSearchParams object also provides several other methods for manipulating the query string, such as set to set the value of a parameter, append to add a new value to a parameter, and delete to remove a parameter.

Note that the URLSearchParams object is not supported in all browsers, so you may need to use a polyfill or a different approach for older browsers.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.