How can you check for a #hash in a URL using JavaS

2018-12-31 05:00发布

I have some jQuery JavaScript code that I want to run only when there is a hash (#) anchor link in a URL. How can you check for this character using JavaScript? I need a simple catch-all test that would detect URLs like these:

  • example.com/page.html#anchor
  • example.com/page.html#anotheranchor

Basically something along the lines of:

if (thereIsAHashInTheUrl) {        
    do this;
} else {
    do this;
}

If anyone could point me in the right direction, that would be much appreciated.

18条回答
萌妹纸的霸气范
2楼-- · 2018-12-31 05:27

Here is a simple function that returns true or false (has / doesn't have a hashtag):

var urlToCheck = 'http://www.domain.com/#hashtag';

function hasHashtag(url) {
    return (url.indexOf("#") != -1) ? true : false;
}

// Condition
if(hasHashtag(urlToCheck)) {
    // Do something if has
}
else {
    // Do something if doesn't
}

Returns true in this case.

Based on @jon-skeet's comment.

查看更多
有味是清欢
3楼-- · 2018-12-31 05:29

Simple:

if(window.location.hash) {
  // Fragment exists
} else {
  // Fragment doesn't exist
}
查看更多
千与千寻千般痛.
4楼-- · 2018-12-31 05:29

sometimes you get the full query string such as "#anchorlink?firstname=mark"

this is my script to get the hash value:

var hashId = window.location.hash;
hashId = hashId.match(/#[^?&\/]*/g);

returns -> #anchorlink
查看更多
余生无你
5楼-- · 2018-12-31 05:30
window.location.hash 

will return the hash identifier

查看更多
只靠听说
6楼-- · 2018-12-31 05:30

Partridge and Gareths comments above are great. They deserve a separate answer. Apparently, hash and search properties are available on any html Link object:

<a id="test" href="foo.html?bar#quz">test</a>
<script type="text/javascript">
   alert(document.getElementById('test').search); //bar
   alert(document.getElementById('test').hash); //quz
</script>

Or

<a href="bar.html?foo" onclick="alert(this.search)">SAY FOO</a>

Should you need this on a regular string variable and happen to have jQuery around, this should work:

var mylink = "foo.html?bar#quz";

if ($('<a href="'+mylink+'">').get(0).search=='bar')) {
    // do stuff
}

(but its maybe a bit overdone .. )

查看更多
深知你不懂我心
7楼-- · 2018-12-31 05:31

Have you tried this?

if (url.indexOf("#") != -1)
{
}

(Where url is the URL you want to check, obviously.)

查看更多
登录 后发表回答