×

Index

JavaScript Tutorial

JavaScript Examples

CSS Tutorial

CSS Examples

How to add or update a query string parameter using JavaScript?

Add/update a query string parameter with JS: In this tutorial, we will learn how to add or update a URL query string parameter using JavaScript? By Pratishtha Saxena, on July 25, 2023

First of all, let's see what is a query string parameter about which we are discussing over here.

What is URL Query String Parameter?

The URL of any website/webpage is usually divided into different parts. The string which follows the "question mark" (?) is called the Query String Parameter. It consists of various key-value pairs and each of them are separated by an ampersand (&). The main task of Query String Parameter is to send data and information over to the servers and fetch data accordingly.

Query string parameter

Add/Update a New Parameter using JavaScript

To add a new parameter to the URL query string parameter, follow the given steps:

  1. If the parameter does not exist, then use the set() method to add a new parameter.
  2. If the parameter to be added has multiple values, then the append() method can be used for the same.

This has been discussed with respect to "URLSearchParams" which are generally recommended for modern browsers.

JavaScript example to add or update a query string parameter

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
  </head>
  
  <body>
    <script type="text/javascript">
      const url = new URL('https://includehelp.com/page');
      const params = new URLSearchParams(url.search);
      
      // Add a new parameter
      params.set('name', 'Alice');
      
      // Add a new parameter
      params.append('city', 'New York');
      
      url.search = params;
      console.log(url.toString());       
    </script>
  </body>
  
</html>

The output of the above example is -

Example | add or update a query string parameter

JavaScript Examples »



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.