Yogesh Chauhan's Blog

How to get query string values in JavaScript? (URL Manipulation using URLSearchParams)

in JavaScript on February 3, 2021

The URLSearchParams provides an interface to work with the data in the query string of a URL.

It also allows manipulation of the query string.

Traditionally, we’ve used regexs and splitting the string to pull out each parameter from the URL. Just like this answers on Stack Overflow.

URLSearchParams API

Given a URL string, we can easily extract parameter values.

Let’s set the parameter string first and print the data using URLSearchParams.

Let’s extract the parameter values.

If there are several values for a param, get returns the first value.

We can also set the parameters. Just like this:

If there are several values, set removes all other parameters with the same name.

We can also append values.

We can also delete one or more parameters

How to modify complete URL?

The URL constructor is helpful to modify the URL.

Take a look at this example

To make actual changes to the URL, we can grab parameters, update their values, then use history.replaceState to update the URL.

// URL: https://example.com?version=1.0
const params = new URLSearchParams(location.search);
params.set('version', 2.0);

window.history.replaceState({}, '', `${location.pathname}?${params}`);
// URL: https://example.com?version=2.0


Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 How to add Read More Read Less Button using JavaScript? #3 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #4 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #5 How to uninstall Cocoapods from the Mac OS? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
How to add Date and Time picker in HTML and get the values using JavaScript?HTMLHow to Use password_hash and password_verify to Secure Your User’s Data (Especially Passwords)?PHPWhat are “holes” in a React component?ReactSQL Basics: What does the asterisk (*) mean in a query?SQL/MySQLClearwater Seafoods – B2C in ChinaMiscellaneousThe SQL UNION OperatorSQL/MySQL