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

How to add parameters to URL in JavaScript?

WBOY
Release: 2023-08-30 21:33:03
forward
1686 people have browsed it

如何在 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)
Copy after login

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)
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template