Node.js 的 URL 模块提供了各种用于 URL 解析和解析的实用程序。
urlObject 的 NodeJS urlObject.hash 属性指定包含前导 ASCII 哈希“#”字符的 URL 片段段。
例如,考虑此 URL “https://user:pass@www.site.com#hash”,urlObject.hash 属性的返回值将为 #hash。
语法
以下是 NodeJS urlObject.hash 属性的语法
urlObject.hash
参数
此属性不接受任何参数。
返回值
此属性检索 URL 的片段段。
例如果指定的 URL 包含片段段,则 hash 属性将检索该段。
在以下示例中,我们尝试从指定的 URL 获取片段段。
注意:要使用 NodeJS urlObject.hash 属性从 URL 中获取片段段,我们首先需要使用 url.parse() 方法解析 URL;否则,哈希段是未定义的。
const url = require('url');
let address = 'https://user:pass@www.Tutorialspoint.com#hashhhhh';
let result = url.parse(address, true);
console.log(result.hash);
输出
正如我们在下面的输出中看到的,NodeJs 哈希属性从 URL 中检索了片段段。
#hashhhhh
例
如果提供的 URL 不包含片段段,则 hash 属性将为 null。
const url = require('url');
let address = 'https://user:pass@www.Tutorialspoint.com';
let result = url.parse(address, true);
console.log(result.hash);
输出
正如我们在下面的输出中看到的,hash 属性为 null,因为 URL 中不涉及片段段。
null
例
如果我们不解析指定的 URL,则 hash 属性将未定义。
在这里,我们尝试在不解析的情况下从提供的 URL 中获取片段段。
const url = require('url');
let address = 'https://user:pass@www.Tutorialspoint.com#hashhhhh';
console.log(address.hash);
输出
正如我们在下面的输出中看到的,hash 属性是未定义的。
undefined