URL parameters (also called query string parameters or URL
variables) are used to send small amounts of data from page to
page, or from client to server via a URL. They can contain all
kinds of useful information, such as search queries, link
referrals, product information, user preferences, and more.
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=sai
#
Accessing 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=sai
You 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=10
You 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); // 10
You 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