URL 类的 NodeJS url.hash 属性获取并设置 URL 的片段部分。
分配给 NodeJS url.hash 属性的值包括百分比编码的无效 URL 字符。用于百分比编码的字符可能与 URL.parse() 和 URL.format() 方法返回的字符略有不同。
语法
以下是 URL 类的 NodeJS 哈希属性的语法
URL.hash
参数
此属性不接受任何参数。
返回值
此属性获取并设置所提供 URL 的片段段。
例我们可以使用 URL.hash 属性获取 URL 的片段部分的值。
在以下示例中,我们尝试获取所提供 URL 的片段部分。
const url = require('url');
const myURL = new URL('https://www.qikepu.com/index.htm#HYD');
console.log(myURL.href);
console.log("Fragment portion value: " + myURL.hash);
输出
执行上述程序后,myURL.hash 属性在 URL 的片段部分返回了值。
https://www.qikepu.com/index.htm#HYD
Fragment portion value: #HYD
Fragment portion value: #HYD
例
我们还可以使用 URL.hash 属性设置 URL 的片段部分的值。
在下面的程序中,我们尝试为给定 URL 的片段部分设置一个新值。
const url = require('url');
const myURL = new URL('https://www.qikepu.com/index.htm#HYD');
console.log(myURL.href);
console.log("The current fragment portion in URL: " + myURL.hash);
myURL.hash = "Delhi";
console.log("After modifying the fragment portion to: " + myURL.hash);
console.log(myURL.href);
输出
正如我们在下面的输出中看到的,myURL.hash 属性修改了给定 URL 的片段部分。
https://www.qikepu.com/index.htm#HYD
The current fragment portion in URL: #HYD
After modifying the fragment portion to: #Delhi
https://www.qikepu.com/index.htm#Delhi
The current fragment portion in URL: #HYD
After modifying the fragment portion to: #Delhi
https://www.qikepu.com/index.htm#Delhi