How to get the query string values in JavaScript
Overview
A query string is used to assign a specific value to the parameter. For example:
https://example.com?name=Shubham&age=22
We have two query string parameters in the above example: name and age. There can be multiple parameters too.
To access the query string in JavaScript, we can use the search property of the location object as follows.
// let's assume current URL is: https://example.com?name=Shubham&age=22window.location.search// here the window.location.search will be:// ?name=Shubham&age=22
Syntax to get query string is JavaScript
To work with query string values in JavaScript, we can use the special object named URLSearchParams as follows:
const queryParams = new URLSearchParams(window.location.search)
Syntax of URLSearchParams()
The URLSearchParams object provides a bunch of methods that can be used to interact with the query parameters. Some of them are as follows.
has(): This is to check if the query string contains a specific parameter.get(): This is to get the value of a specific parameter.getAll(): This is to get an array of all the values in the query string.forEach(): This is to iterate over the parameters of the query string.keys(): This is to iterate over the keys of the query string.values(): This is to iterate over the values of the query string.
Example
Let's see an example of the URLSearchParams() object in the code snippet below.
// let's assume current URL is: https://example.com?name=Shubham&age=22const queryParams = new URLSearchParams(window.location.search);// 1. iterate over the keysfor (const key of queryParams.keys()) {console.log(key);}/* outputnameage*/// 2. iterate over the valuesfor (const value of queryParams.values()) {console.log(value);}/* outputShubham22*/// 3. check if the query string contains "contact"const containsContact = queryParams.has('contact');console.log(containsContact)/* outputfalse*/// 4. get the value of "name"const name = queryParams.get('name');console.log(name)/* outputShubham*/
Explanation
- Line 3: We use the
URLSearchParamsobject to get the query string parameters. - Lines 6–8: We use the
keys()method to iterate over the keys of the query string parameters. The output is mentioned in lines 10-11. - Lines 15–17: We use the
values()method to iterate over the values of the query string parameters. The output is mentioned in lines 19-20. - Lines 24–25: We use the
has()method to check if the query string containscontact. The output will be as mentioned in line 27. - Lines 31–32: We use the
get()method to get the value of the parametername. The output will be as mentioned in line 34.