• Node.js Video Tutorials

NodeJS urlSearchParams.getAll() 方法



NodeJS urlSearchParams.getAll() 方法 用於獲取查詢字串中指定名稱的所有值。

URLSearchParams API 提供了訪問和讀取 URL 查詢的方法。此類也存在於全域性物件上。

讓我們考慮一個 YouTube URL('https://www.youtube.com/watch?t=RSUgBMA-8Ks?t= TSUgRRMA-95'),其中“?”之後的部分稱為查詢片段。在這個查詢中,(t) 是名稱,(RSUgBMA-8Ks) 是值。它們一起構成一個鍵值對。同樣,查詢字串中有兩個鍵值對,它們都具有名稱 (t) 但值不同。因此,如果對名稱 (v) 使用 getAll() 方法,它將返回所有值。

語法

以下是NodeJS URLSearchParams.getAll() 方法的語法

URLSearchParams.getAll(name)

引數

  • name: 指定要返回的引數的名稱。

返回值

此方法返回一個數組,其中包含作為引數傳遞的給定name的所有值。如果不存在名稱為 name 的鍵值對,則返回一個空陣列。

示例

如果要搜尋的名稱在查詢字串中出現多次,則 NodeJS urlSearchParams.getAll() 方法會將其所有出現的值作為陣列返回。

在下面的示例中,我們嘗試獲取查詢字串中名為“title”的鍵的所有值。

const url = require('node:url');

const MyUrl = new URL('https://tutorialspoint.tw?title=1&title=2&body=3&title=4');
console.log("URL: ", MyUrl.href);

const Params = new URLSearchParams('title=1&title=2&body=3&title=4');
console.log("Query string: " + Params);

console.log("Trying to get all values for the key 'body'.....");
console.log("The value is: " + JSON.stringify(Params.getAll("title")));

輸出

從下面的輸出中可以看到,NodeJS getAll() 方法返回了名稱(“title”)的所有值。

URL:  https://tutorialspoint.tw/?title=1&title=2&body=3&title=4
Query string: title=1&title=2&body=3&title=4
Trying to get all values for the key 'body'.....
The value is: ["1","2","4"]

示例

如果要搜尋的名稱不存在於查詢字串中,則 getAll() 方法將返回一個空陣列。

在下面的示例中,我們嘗試獲取名稱(“contactUs”)的值。

const url = require('node:url');

const MyUrl = new URL('https://tutorialspoint.tw?title=1&header=2&body=3&footer=4');
console.log("URL: ", MyUrl.href);

const Params = new URLSearchParams('title=1&header=2&body=3&footer=4');
console.log("Query string: " + Params);

console.log("Trying to get all values for the key 'contactUs'.....");
console.log("The value is: " + JSON.stringify(Params.getAll("contactUs")));

輸出

getAll() 方法返回了一個空陣列,因為要搜尋的名稱不存在於查詢字串中。

URL:  https://tutorialspoint.tw/?title=1&header=2&body=3&footer=4
Query string: title=1&header=2&body=3&footer=4
Trying to get all values for the key 'contactUs'.....
The value is: []
nodejs_url_module.htm
廣告