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
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)
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.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*/
URLSearchParams
object to get the query string parameters.keys()
method to iterate over the keys of the query string parameters. The output is mentioned in lines 10-11.values()
method to iterate over the values of the query string parameters. The output is mentioned in lines 19-20.has()
method to check if the query string contains contact
. The output will be as mentioned in line 27.get()
method to get the value of the parameter name
. The output will be as mentioned in line 34.