如何在 JavaScript 中向 URL 新增一個引數?
在本文中,你將瞭解如何在 JavaScript 中向 URL 新增引數。有兩種方法可以向 URL 新增引數:append() 方法和 set() 方法。
append() 方法用於專門向 URL 新增鍵值對。
set() 方法將值新增到特定鍵。如果鍵不存在,則建立一個新鍵。如果存在多個鍵,則其中一個的值將更新,而其他值將被刪除。
示例 1
讓我們在這個示例中看看 append() 方法
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)
說明
步驟 1 - 定義一個帶引數的 URL。
步驟 2 - 使用 append() 方法向 URL 新增新引數。
步驟 3 - 顯示結果。
示例 2
讓我們在這個示例中看看 set() 方法
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)
說明
步驟 1 - 定義一個帶引數的 URL。
步驟 2 - 使用 append() 方法向 URL 新增新引數。
步驟 3 - 顯示結果。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP