NodeJS - url.username 属性


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

Node.js URL 模块提供了多个用于 URL 解析和解析的实用程序。

语法

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


 URL.username

参数

此方法不接受任何参数。

返回值

此属性获取并设置 URL 的用户名部分。

例

如果我们将完整的 URL 分配给 NodeJS url.username 属性,它将获取 URL 的用户名部分。

在以下示例中,我们尝试获取所提供 URL 的用户名段。


const http = require('url');

const myURL = new URL('https://Nikhil:hyd@qikepu.com');
console.log("Username portion of the URL is: " + myURL.username);

输出

执行上述程序后,username 属性从提供的 URL 中获取用户名段。

Username portion of the URL is: Nikhil

例

username 属性允许为给定 URL 中的用户名段设置有效值。

在下面的程序中,我们尝试为输入 URL 中的用户名段设置一个值。


const http = require('url');

const myURL = new URL('https://Nikhil:hyd@qikepu.com');
console.log("The URL: " + myURL.href);
console.log("Username portion of the URL is: " + myURL.username);

myURL.username = "Nikhilesh";
console.log("Trying to change the username to - " + myURL.username);
console.log("The URL after modifying: " + myURL.href);

输出

正如我们在下面的输出中看到的,输入 URL 的用户名段被修改了

The URL: https://Nikhil:hyd@qikepu.com/
Username portion of the URL is: Nikhil

Trying to change the username to - Nikhilesh
The URL after modifying: https://Nikhilesh:hyd@qikepu.com/

例

如果 URL 的用户名部分中出现任何无效的 URL 字符,则这些字符将进行百分比编码。

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


const http = require('url');

const myURL = new URL('https://Ni`khi`l:hyd@qikepu.com');
console.log("The URL: " + myURL.href);
console.log("Username portion of the URL is: " + myURL.username);

输出

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

The URL: https://Ni%60khi%60l:hyd@qikepu.com/
Username portion of the URL is: Ni%60khi%60l