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


Sources:


Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
Order By and Group By in PostgresPostgresHow to Make CSS Lists Bullets Smaller?CSSWordPress: How to get field values in Advanced Custom Fields?WordPressHow to create rotating texts using JavaScript and CSS?CSSHow to create a flip pricing table using CSS and JavaScript?CSSAdd animation to your skills bar using CSSCSS