How to Get URL Parameters in JavaScript

How to get all or one of the parameters from the URL of the current page in JavaScript with vanilla JavaScript.

Published Categorized as JavaScript, Web Dev

Suppose you’re building a website or a web application and, for some reason, you need to get all or one of the URL parameters of the current page.

What’s the best way to do that?

To get the URL parameters of the current page in JavaScript, reference the search property of the window.location object.

This will return a USVString starting with a question mark (?) and containing all of the URL parameters of the current page. You can use it as you’d do a regular string in JavaScript.

Once you’ve referenced the search property of the Location object and you’ve obtained its value, you can store it in a constant or variable for future use, or get the values of individual URL parameters as you need.

How It Works

Let’s say you’re on a web page with the following URL:

https://site.com?section=articles&article=42

To get the value of the URL parameters (basically, everything that follows the question mark), reference the search property of the Location object in your JavaScript code:

window.location.search

In the case of our example, this will return a USVString with a value of ?section=articles&article=42.

Ways to Use It

Store It in a Constant or Variable

The simplest, most straightforward way to use this property is to store its values in a constant or a variable, so that you can reference that constant or variable later on in your code:

// Store URL parameters in constant
const urlParams = window.location.search;

// Store URL parameters in variable
var urlParams = window.location.search;

Store the URL parameters in a constant if they won’t change during the user’s interaction with the current page. Since you can’t redeclare a constant, if you try to save the new values in urlParams, you will get an error stating that urlParams has already been declared.

If the URL parameters of the current page will change, store them in a variable. Declaring the variable with the var statement makes it accessible throughout the entire function; the let statement makes it accessible only within the block and all of its sub-blocks.

Get a Single URL Parameter

To get a single parameter from the URL of the current page, create a new query string using the URLSearchParams() method.

Keeping to the example URL (https://site.com?section=articles&article=42) from above, the following code will output “articles” to the console:

// Create urlParams query string
var urlParams = new URLSearchParams(window.location.search);

// Get value of single parameter
var sectionName = urlParams.get('section');

// Output value to console
console.log(sectionName);

Simply replace 'section' with the URL parameter whose value you need to obtain, keeping the brackets, and you’re pretty much done.

Learn new skills:

Leave a comment

Your email address will not be published.