• Node.js Video Tutorials

NodeJS - urlSearchParams.get() 方法



NodeJS urlSearchParams.get() 方法用於從 URLSearchParams 類中檢索查詢字串中指定名稱的值。

可以使用URLSearchParams API 讀取和寫入 URL 的查詢部分。此類也存在於全域性物件上。

為了更好地理解此方法,讓我們來看一個真實的例子。考慮這個 URL(‘https://www.youtube.com/watch?v=towpH780PT0’),其中 'v=towpH780PT0' 被稱為查詢段。在這個查詢中,(v) 是名稱,(towpH780PT0) 是值。它們一起構成一個名稱-值對。

語法

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

URLSearchParams.get(name)

引數

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

返回值

此方法返回作為引數傳遞的給定name 的字串值。

  • 如果有多個具有給定名稱的名稱-值對,此方法將返回第一對中的值。

  • 如果沒有名稱為name 的對,則返回null

示例

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

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

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

const Params = new URLSearchParams('one=1&two=2&three=3');
console.log("Query string: " + Params);

console.log("Trying to get the value of key 'two'.....");
console.log("The value is: " + Params.get("two"));

輸出

執行上述程式後,NodeJS get() 方法將返回鍵“two”的值。

URL:  https://tutorialspoint.tw/?one=1&two=2&three=3
Query string: one=1&two=2&three=3
Trying to get the value of key 'two'.....
The value is: 2

示例

如果要在查詢字串中搜索的名稱多次出現,get() 方法將返回其第一次出現的值。

在下面的程式中,我們嘗試獲取查詢字串中名稱“two”的值。

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

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

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

console.log("Trying to get the value of the first key 'two'.....");
console.log("The value is: " + Params.get("two"));

輸出

正如我們在輸出中看到的,get() 方法返回第一次出現的值。

URL:  https://tutorialspoint.tw/?two=1&two=2&two=3
Query string: two=1&two=2&two=3
Trying to get the value of the first key 'two'.....
The value is: 1

示例

如果要在查詢字串中搜索的名稱不存在,get() 方法將返回 null。

在下面的示例中,我們嘗試獲取查詢字串中不存在的名稱的值。

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

const MyUrl = new URL('https://tutorialspoint.tw?HTML=499&NODEJS=999&CSS=699');
console.log("URL: ", MyUrl.href);

const Params = new URLSearchParams('HTML=499&NODEJS=999&CSS=699');
console.log("Query string: " + Params);

console.log("Trying to get the value of the first key 'JavaScript'.....");
console.log("The value is: " + Params.get("JavaScript"));

輸出

正如我們在輸出中看到的,get() 方法返回 null。

URL:  https://tutorialspoint.tw/?HTML=499&NODEJS=999&CSS=699
Query string: HTML=499&NODEJS=999&CSS=699
Trying to get the value of the first key 'JavaScript'.....
The value is: null
nodejs_url_module.htm
廣告