YogeshChauhan . com

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 How to Use SQL MAX() Function with Dates? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

Jun 16 What are Stored Procedures for SQL Server? Jun 16 What are Class Constants in PHP? Jun 15 A short basic guide on states in React Jun 15 How to define constants in PHP? Jun 15 How to define visibility for a property in PHP? Jun 15 How to use @if and @else in SCSS?

You might also like these

Relative Length Units in CSSCSSWhat Does Host-Based Intrusion Detection System (HIDS) Mean and What Are Some Advantages Over NIDS?MiscHow to create Glowing Text using CSS?CSSHow to get start index and end index (as int) of substring in Swift?SwiftHow to create a for loop in SCSS (Sass)?SCSSHow to get previous days or next days in PHP?PHP