You can get query string values in JavaScript by using the URLSearchParams
object. The URLSearchParams
the object provides a convenient way to extract the query string from a URL and access the values of individual parameters.
Here’s an example of using URLSearchParams
to extract the query string from a URL and get the value of a specific parameter:
const url = new URL(window.location.href);
const searchParams = new URLSearchParams(url.search);
const parameterValue = searchParams.get('parameterName');
In this example, url
is a URL
an object that represents the current URL. The searchParams object is created by passing the search property of the URL object to the URLSearchParams constructor. Finally, the get method of the searchParams the object is used to get the value of a specific parameter in the query string.
If you need to support older browsers that don’t have URLSearchParams
, you can use a regular expression to extract the query string from the URL and use split
and indexOf
methods to access the values of individual parameters. Here’s an example:
const queryString = window.location.search;
const parameterValue = (new RegExp('[?&]' + 'parameterName' + '=([^&#]*)').exec(queryString) || [null, ''])[1];
In this example, queryString
is the query string of the current URL. The regular expression is used to extract the value of the parameterName
parameter from the query string and the value is stored in the parameterValue
variable.