how can I get # hashtag part of the URL using jque

2019-09-21 09:27发布

问题:

This is my URL:

www.example.com/contact#test

Now I need to test. According to the research, I've found a site related to my problem, and I realized that I should use of hash for get test from my url. something like this:

var url = www.example.com/contact#test;
var anchor = url.hash;
alert(anchor);

but when I use of alert for anchor, it shows me undefined. anyway how can I get test from my url ?

回答1:

The most efficient way is using pure JavaScript

var hashValue = window.location.hash.substr(1);


回答2:

Easiest way to do is using split, if your URL has test only after the #. And also nothing other that test after the #.

var url = 'www.example.com/contact#test';
var anchor = url.split('#');
alert(anchor[1]);



回答3:

var url = new URL("http://www.example.com/contact#test");
console.log(url.hash.substring(1));