How to get query parameters from a URL in JavaScript
In this tutorial, we are going to learn how to access the query parameters from a URL using JavaScript.
Query Parameters
Query parameters are added at the end of a URL using question mark ? followed by the key=value
pairs.
Example:
localhost:3000/?name=saiAccessing the query parameters
To access the query parameters of a URL inside the browser, using JavaScript, we can use the URLSeachParams interface that contains a get() method to work with it.
Here is an example:
Url:
localhost:3000/?name=saiYou can get the value of a name parameter from the above url like this:
// window.location.search = ?name=sai
const params = new URLSearchParams(window.location.search);
const name = params.get("name");
console.log(name); // "sai"If you have multiple parameters in a URL which is passed using & operator:
localhost:3000/?name=sai&score=10You can access it like this:
// window.location.search = ?name=sai&score=10
const params = new URLSearchParams(window.location.search);
const name = params.get("name");
const name = params.get("score");
console.log(name); // "sai"
console.log(score); // 10You can also check, if a URL contains specified parameters or not by using the has() method.
The has() method returns boolean value true if a parameter name exists; otherwise it returns false.
params.has("name"); // true
params.has("place"); // false

