Home >Web Front-end >JS Tutorial >How to add parameters to URL in JavaScript?

How to add parameters to URL in JavaScript?

WBOY
WBOYforward
2023-08-30 21:33:031671browse

如何在 JavaScript 中向 URL 添加参数?

In this article, you will learn how to add parameters to a URL in JavaScript. There are two ways to add parameters to the url: the append() method and the set() method.

The append() method is used to specifically add key-value pairs to the url.

set() method adds a value to a specific key. If the key does not exist, a new key is created. If multiple keys exist, update the value of one key and delete the others.

Example 1

Let’s take a look at the append() method in this example

let inputUrl = new URL('https://urlExample.com?key1=value1');
let inputParams = new URLSearchParams(inputUrl.search);
console.log("The parameters of the url is defined as: ", inputParams)

inputParams.append('key2', 'value2');

console.log("The url after adding adding the parameters is: ",inputParams)

illustrate

  • Step 1 - Define the url with parameters.

  • Step 2 - Use the append() method to add new parameters to the url.

  • Step 3 - Display the results.

Example 2

Let’s look at the set() method in this example

let inputUrl = new URL('https://urlExample.com?key1=value1');
let inputParams = new URLSearchParams(inputUrl.search);
console.log("The parameters of the url is defined as: ", inputParams)

inputParams.set('key2', 'value2');

console.log("The url after adding adding the parameters is: ",inputParams)

illustrate

  • Step 1 - Define the url with parameters.

  • Step 2 - Use the append() method to add new parameters to the url.

  • Step 3 - Display the results.

The above is the detailed content of How to add parameters to URL in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete