YogeshChauhan.com
How to get query string values in JavaScript? (URL Manipulation using URLSearchParams)
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:

dreamhost

Leave a Reply

Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 How to set opacity or transparency using CSS? #3 Pagination in CSS with multiple examples #4 How to make HTML form interactive and using CSS? #5 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #6 How to uninstall Cocoapods from the Mac OS?

Recently Posted

Mar 2 How to zoom an element on hover using CSS? Mar 2 the box-sizing property in CSS Mar 2 WordPress: How to access first and random row values from a repeater field in ACF? Mar 1 The basics of CSS Box model Feb 27 WordPress: How to display slider repeater fields in ACF? Feb 26 Simple Page Hit Counter in PHP

You might also like these

Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software”MiscWhat’s a repository on Github?MiscOpen Source Security Tools for Defense SecurityMiscUnary Operators in JavaScriptJavaScriptinclude, include_once, require, require_once in PHPPHPWhat is a Strict Requirement in PHP 7 Function Declarations?PHP