NodeJS - url.search 属性


URL 类的 NodeJS url.search 属性获取并设置 URL 的序列化查询部分。如果无效的 URL 字符出现在分配给 username 属性的值中,则它们将采用百分比编码。要进行百分比编码的字符选择可能与 url.parse() 和 url.format() 方法生成的字符略有不同。

Node.js URL 模块提供了几个用于 URL 解析和解析的实用程序,search 属性就是其中之一。

语法

以下是 URL 类的 NodeJS search 属性的语法


 URL.search

参数

此属性不接受任何参数。

返回值

此属性设置并获取 URL 的查询部分。

例

如果我们将 URL 分配给 NodeJS url.search 属性,它将从给定的 URL 获取查询部分。

在以下示例中,我们尝试从输入 URL 获取查询段。


const http = require('url');

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

输出

执行上述程序后,search 属性从输入 URL 中获取查询段。

The URL: https://www.qikepu.com/?Node.js-articles
Query portion of the URL is: ?Node.js-articles

例

我们可以为所提供的 URL 的查询部分设置任何有效值。

在下面的程序中,我们尝试为输入 URL 的查询部分设置一个值。


const http = require('url');

const myURL = new URL('https://www.qikepu.com/?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://www.qikepu.com/?Node.js-articles
Query portion of the URL is: ?Node.js-articles

Modifying the query portion to- ?JavaScript-Articles
After modifying: https://www.qikepu.com/?JavaScript-Articles

例

如果 URL 的查询部分包含任何无效的 URL 字符,则这些字符将进行百分比编码。

在以下示例中,我们将在用户名部分分配一个包含无效字符的 URL。


const http = require('url');

const myURL = new URL('https://www.qikepu.com/?你好-Articles');

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

输出

正如我们在输出中看到的,URL 中的无效字符被进行了百分比编码。

The URL: https://www.qikepu.com/?%E4%BD%A0%E5%A5%BD-Articles
Value in query portion: ?%E4%BD%A0%E5%A5%BD-Articles