How to Get Query String Values in JavaScript

To get a query string values in JavaScript, you can use the “window.location.search” property.

To work with the query string, you can use the special object “URLSearchParams”.

const urlParams = new URLSearchParams(location.search);

To iterate URLSearchParams iterable object to get the query string parameters, you can use the “for…of” loop.

const urlParams = new URLSearchParams(location.search);

for (const [key, value] of urlParams) {
   console.log(`${key}:${value}`);
}

If the location.search value is: ‘?type=list&page=19’ then, the above code returns the following output.

type: list
page: 19

URLSearchParams methods

Here are 3 methods that return iterators of parameter keys, values, and entries:

  1. keys(): It returns an iterator that iterates over the parameter keys.
  2. values(): It returns an iterator that iterates over the parameter values.
  3. entries(): It returns an iterator that iterates over the (key, value) pairs of the parameters.
  4. has(): This method is used to check if the query string contains a specific parameter.
  5. get(): This method is used to get the value of a specific parameter.
  6. getAll(): This method is used to get an array of all the values in the query string.
  7. forEach(): This method is used to iterate over the parameters of the query string.

URLSearchParams.keys()

const urlParams = new URLSearchParams('?type=list&page=19&data=21');

for (const key of urlParams.keys()) {
  console.log(key);
}

Output

type
page
data

URLSearchParams.values()

const urlParams = new URLSearchParams('?type=list&page=19&data=21');

for (const value of urlParams.values()) {
  console.log(value);
}

Output

list
19
21

URLSearchParams.entries()

const urlParams = new URLSearchParams('?type=list&page=19&data=21');

for (const entry of urlParams.entries()) {
  console.log(entry);
}

Output

[ 'type', 'list' ]
[ 'page', '19' ]
[ 'data', '21' ]

How to check if a query string parameter exists

To check if a query string parameter exists in JavaScript, you can use the “URLSearchParams.has()” method. The URLSearchParams.has() method returns true if a parameter with a specified name exists; false otherwise.

const urlParams = new URLSearchParams('?type=list&page=19&data=21');

console.log(urlParams.has('data'));
console.log(urlParams.has('base')); 

Output

true
false

That’s it.

Leave a Comment