如何在 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 - 顯示結果。

更新於: 16-02-2023

26K+ 條瀏覽

開啟你的 職業

完成此課程即可獲得認證

開始
廣告
© . All rights reserved.