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:


amazon

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 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS? #Aug 1 What is Zdog? #Aug 1 How to add before after image effect using pure CSS? #Jul 31 Add animation to your skills bar using CSS #Jul 31 Use SwiperJS to create mobile touch sliders fast
You might also like these
Why do we need HAVING Clause in SQL?SQL/MySQLHow to remove trailing characters from a string using JavaScript?JavaScriptA few HTML coding standards from WordPressHTMLHow to redirect or load a new document using JavaScript?JavaScriptHow to create rotating texts using JavaScript and CSS?CSSAll possible ways you can Insert Data in PostgresPostgres