get url params with js

Get URL Params with JS

Have you ever needed to extract data from the URL in your JavaScript code? Maybe you want to retrieve a user ID or a product name from the URL to display specific information on a page. In this blog post, I will show you how to get URL parameters with JavaScript.

The easiest way to get URL parameters is by using the window.location.search property. This will return the query string part of the URL, which includes any parameters and their values.


const params = new URLSearchParams(window.location.search);
const productId = params.get('id');
console.log(productId); // prints the value of the 'id' parameter

In the above code, we first create a new instance of the URLSearchParams object and pass in window.location.search as its argument. Then we can use the get() method to retrieve the value of a specific parameter, in this case, 'id'.

Method 2: Using Regular Expressions

If you prefer regular expressions, you can extract URL parameters using a pattern match. Here's an example:


const url = 'https://example.com/page.html?id=123&name=John';
const regex = /[?&]([^=#]+)=([^&#]*)/g;
let match;

while ((match = regex.exec(url)) !== null) {
  console.log(match[1] + ': ' + match[2]);
}

In this code, we first define a regular expression pattern that matches any characters after a question mark or ampersand until a equals sign, followed by any characters that are not ampersands or hash symbols. We then use the exec() method to execute this pattern against the URL and return an array of matches. We loop through this array and log the parameter name and its value.

Method 3: Using libraries

If you prefer to use a library, there are many available that provide methods for working with URLs and query strings. Examples include:

These libraries provide simple API for parsing URLs and query strings, making it easy to retrieve parameters and their values.

In conclusion, there are several ways to get URL parameters with JavaScript. Whether you prefer using built-in properties like window.location.search, regular expressions, or third-party libraries, you can easily extract data from the URL and use it in your code.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe