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:
- keys(): It returns an iterator that iterates over the parameter keys.
- values(): It returns an iterator that iterates over the parameter values.
- entries(): It returns an iterator that iterates over the (key, value) pairs of the parameters.
- has(): This method is used to check if the query string contains a specific parameter.
- get(): This method is used to get the value of a specific parameter.
- getAll(): This method is used to get an array of all the values in the query string.
- 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.

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.