In HTTP URL parameter is a portion of a URL that follows the question mark (?) and is used to pass data to a web server. URL parameters are typically used to send additional information to a web server when requesting a specific resource, such as a webpage or an API endpoint.

URL parameters consist of key-value pairs, where the key represents the parameter name, and the value represents the data associated with that parameter. Multiple parameters can be included in a URL by separating them with an ampersand (&).

How to get the URL parameter in JavaScript?

The easiest way is to use the URLSearchParams utility method which comes as standard in the language itself. For example, let's say you have the following URL https://example.com/category/how-to?page=2 and you want to get the page parameter. You can do that like so

const url = 'https://example.com/category/how-to?page=2';

// Split the URL by ? to extract parameters only
const params = url.split('?');

const searchParams = new URLSearchParams(params[1]);
console.log(searchParams.get('page'));
// Expected output 2

Note that UrlSearchParams expects parameters only and not a full URL. This is why in the example we first extract the parameters portion and then we pass that to the constructor.

Here is a more extensive example using all of the methods of UrlSearchParams

const query = 'q=pants&category=clothes';
const params = new URLSearchParams(query);

// Iterate over the parameters
for (const p of params) {
  console.log(p);
}
// Expected output
// pants
// clothes

console.log(params.has("pants")); // true
console.log(params.has("car")); // false
console.log(params.getAll("category")); // ["clothes"]

// Append parameter
params.append("category", "promotions");

console.log(params.getAll("category")); // ["clothes", "promotions"]
console.log(params.toString()); 
// Expected output 'q=pants&category=clothes&category=promotions'

console.log(params.set("q", "shirts"));
console.log(params.toString()); // "q=shirts&category=clothes&category=promotions"

// Delete parameter
params.delete('category');

console.log(params.toString()); // "q=shirts"

How to get the URL parameter for the current page?

Using the window.location.search you can get the parameters of the current page.

// lets say your browser is at https://example.com/category/how-to?page=1&user=5

let searchParams = new URLSearchParams(window.location.search);

console.log(searchParams.page);
// Expected output 1

console.log(searchParams.user);
// Expected output 5