Get Parameters from URL with JavaScript: Tips and Best Practices

Reading URL parameters is a usual thing in web development, especially when making dynamic web pages that depend on what users type in. URL parameters help different parts of a website communicate with each other. They’re handy for adjusting how a page looks or works based on what a user likes or does.

JavaScript supports a number of methods, each with advantages and disadvantages, for reading parameters from URLs.

Built-in URLSearchParams API in JavaScript, regular expressions, and string manipulation techniques are three methods for extracting URL parameters that are covered in this article.

By the end of this article, you will know more about how to get URL parameters in JavaScript and which method is best for your specific use case.

Get Parameters from URL with JavaScript: Tips and Best Practices


Table of Content

  1. Get URL Parameters in JavaScript using URLSearchParams API
  2. Get URL Parameters from Full URL in JavaScript using Regular Expression
  3. Using Split() Method to Get Query String Parameters in JavaScript
  4. Conclusion

1. Get URL Parameters in JavaScript using URLSearchParams API

You can easily parse and work with URL query strings using the built-in JavaScript API called URLSearchParams.

Create a new instance of the URLSearchParams object using the window.location.search property, it contains the query string portion of the current URL, to use it to read URL parameters.

Before reading the parameter first check if the parameter exists in the URL or not. If exists then call the get() method on the URLSearchParams object, pass the name of the parameter that needs to be read. It will return the value of the parameter.

Pros:

  • Simple and easy to use
  • Built-in API, no need to create a regular expression or custom parsing logic
  • Provides additional methods for manipulating query strings

Cons:

  • Requires a modern browser that supports the URLSearchParams API

Here, is an example –

Stored current page URL in currentPageURL variable and static URL in pageURL variable, it works with both.

// Current page URL
var currentPageURL = window.location.search;

// URL
var pageURL = "https://example.com/index.php?userid=21&name=yogesh&city=bhopal";

// Parameter that needs to read from URL
var readParam = "userid";

// URLSearchParams Object
var urlParams = new URLSearchParams(currentPageURL);

// Check parameter exists and read value
var paramValue = "";
if(urlParams.has(readParam)){
      paramValue = urlParams.get(readParam);
}

console.log(paramValue);

It will give the following output in the browser console –

21

2. Get URL Parameters from Full URL in JavaScript using Regular Expression

Regular expressions in JavaScript are great for working with strings. If you want to read URL parameters from a query string using regular expressions, just make a pattern that matches the parameter name and catches its value.

Then use the exec() method on the regular expression with the window.location.search property, which returns an array of matches, and extracts the value of the captured group.

Pros:

  • Can be used in any JavaScript environment
  • Provides full control over parsing logic
  • Can handle complex parameter values, such as encoded characters

Cons:

  • Requires knowledge of regular expressions
  • Can be more complex and error-prone than other methods
  • Can be slower than built-in methods for large query strings

Here, is an example –

// Current page URL
var currentPageURL = window.location.search;

// URL
var pageURL = "https://example.com/index.php?userid=22&name=sunil&city=indore";

// Parameter that needs to read
var readParam = "name";

// Regular expression
const regex = new RegExp('[?&]' + encodeURIComponent(readParam) + '=([^&#]*)');

var paramValue = "";
// Check parameter exists and read value
if(regex.test(currentPageURL)) {
     var paramValue = regex.exec(currentPageURL)[1];
}

console.log(paramValue);

It will give the following output in the browser console –

sunil

3. Using Split() Method to Get Query String Parameters in JavaScript

A string can be divided into an array of substrings using a separator using the built-in JavaScript method split().

To read query string parameters using split(), first extract the query string part of the URL from the pageURL variable, remove the initial ? character, and split the remaining string into an array of key-value pairs using the & separator.

Then loop on the array and extract the value of the parameter with the specified name.

Pros:

  • Can be used in any JavaScript environment
  • Simple and easy to understand
  • Provides full control over parsing logic

Cons:

  • Cannot handle complex parameter values, such as encoded characters, without additional decoding logic
  • Can be slower than built-in methods for large query strings
  • May require additional parsing logic for key-value pairs that have multiple values

Here, is an example –

// Current page URL
var currentPageURL = window.location.search;

// URL
var pageURL = "https://example.com/index.php?userid=23&name=vishal&city=jaipur";

// Parameter that needs to read from URL
var readParam = "city";

// Split the URL
var params = pageURL.substr(1).split('&');
var paramValue = '';

// Loop and read parameter
params.forEach(param => {
     let keyValue = param.split('=');
     if (keyValue[0] === readParam) {
           paramValue = decodeURIComponent(keyValue[1].replace(/\+/g, ' '));
     }
});

console.log(paramValue);

It will give the following output in the browser console –

jaipur

4. Conclusion

When creating web applications, you can get parameter from URL in JavaScript using a variety of techniques.

The URLSearchParams API is a quick and easy way to read query string parameters, but regular expressions offer a more robust and flexible method for matching and extracting parameter values from the URL. The split() method, in addition, enables you to extract query string parameters as key-value pairs and iterate through them to find the necessary value.

Your particular use case and personal preferences will determine which approach you take.

You can view more JavaScript tutorials on this blog.

If you found this tutorial helpful then don't forget to share.

Leave a Comment