在javascript中从一个url中获取#符号后的片段值的方法

222 阅读1分钟

有时,我们想在javascript中从一个url中获取#符号后的片段值

例如,你有一个网址

abc.com/about#contact

使用javascript,获得一个给定的url的值,如下所示。

contact

在html页面中,碎片化的url值可以用来在页面的不同部分或标签之间进行导航。

如何在javascript中获得碎片化的url值

我们有多种方法可以获取碎片化的url值

  • 使用window.location.hash属性

window.location.hash属性返回片段值

如果页面的网址是abc.com/about#contact

console.log(window.location.hash) //returns  #contact value

如果页面的网址是abc.com/about

console.log(window.location.hash) //returns empty value

如果url包含字符串url,使用substring()方法

var strUrl = "www.abc.com/about#contact";
var hash = strUrl.substring(strUrl.indexOf('#')+1);
console.log(hash); // returns contact

另一种方法是使用url对象

var url = new URL('https://abc.com/about#contact');
console.log(url.hash); // returns #contact

使用分离器(#)符号分割字符串,并使用index=1返回数组中的第二个元素。

let strUrl = "www.abc.com/about#contact";
let fragmentValue=strUrl.split('#')[1]
console.log(fragmentValue);

总结

通过实例学习了从javascript中查找片段值的多种方法