Categories
React Answers

How to get parameter value from query string with JavaScript?

Spread the love

We can get parameter values from a query string in JavaScript by utilizing the URLSearchParams API, which allows we to parse and manipulate URL query parameters easily.

Here’s how we can do it:

// Assume the URL is something like: http://example.com/page?param1=value1&param2=value2

// Get the query string from the URL
const queryString = window.location.search;

// Create a new URLSearchParams object with the query string
const urlParams = new URLSearchParams(queryString);

// Get the value of a specific parameter
const param1Value = urlParams.get('param1'); // Returns "value1"
const param2Value = urlParams.get('param2'); // Returns "value2"

This code will extract the parameter values value1 and value2 from the query string param1=value1&param2=value2. Wecan then use these values as needed in our JavaScript code.

Note: This method is supported in modern browsers, but if we need to support older browsers, we might need to use a polyfill or alternative methods like regular expressions to parse the query string.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *