• Node.js Video Tutorials

NodeJS - url.search 屬性



URL 類 的 NodeJS url.search 屬性 獲取並設定 URL 的序列化查詢部分。如果無效的 URL 字元出現在分配給 username 屬性的值中,則會對其進行百分比編碼。百分比編碼的字元選擇可能與 url.parse() 和 url.format() 方法生成的字元略有不同。

Node.js URL 模組提供了多個用於 URL 解析和分析的實用程式,而 search 屬性就是其中之一。

語法

以下是 NodeJS URL 類 的 search 屬性 的語法

URL.search

引數

此屬性不接受任何引數。

返回值

此屬性設定並獲取 URL 的查詢部分。

示例

如果我們將 URL 分配給 NodeJS url.search 屬性,它將從給定的 URL 獲取查詢部分。

在下面的示例中,我們嘗試從輸入 URL 獲取查詢段。

const http = require('url');

const myURL = new URL('https://tutorialspoint.tw/?Node.js-articles');
console.log("The URL: " + myURL.href);
console.log("Query portion of the URL is: " + myURL.search);

輸出

執行上述程式後,search 屬性將從輸入 URL 獲取查詢段。

The URL: https://tutorialspoint.tw/?Node.js-articles
Query portion of the URL is: ?Node.js-articles

示例

我們可以將任何有效值設定為提供的 URL 的查詢部分。

在下面的程式中,我們嘗試將值設定為輸入 URL 的查詢部分。

const http = require('url');

const myURL = new URL('https://tutorialspoint.tw/?Node.js-articles');
console.log("The URL: " + myURL.href);
console.log("Query portion of the URL is: " + myURL.search);

myURL.search = "JavaScript-Articles";
console.log("Modifying the query portion to- " + myURL.search);
console.log("After modifying: " + myURL.href);

輸出

正如我們在下面的輸出中看到的,URL 的查詢段已修改。

The URL: https://tutorialspoint.tw/?Node.js-articles
Query portion of the URL is: ?Node.js-articles

Modifying the query portion to- ?JavaScript-Articles
After modifying: https://tutorialspoint.tw/?JavaScript-Articles

示例

如果 URL 的查詢部分包含任何無效的 URL 字元,則這些字元將被百分比編碼。

在下面的示例中,我們分配了一個在使用者名稱部分包含無效字元的 URL。

const http = require('url');

const myURL = new URL('https://tutorialspoint.tw/?你好-Articles');

console.log("The URL: " + myURL.href);
console.log("Value in query portion: " + myURL.search);

輸出

正如我們在輸出中看到的,URL 中的無效字元已進行百分比編碼。

The URL: https://tutorialspoint.tw/?%E4%BD%A0%E5%A5%BD-Articles
Value in query portion: ?%E4%BD%A0%E5%A5%BD-Articles
nodejs_url_module.htm
廣告