How can you check for a #hash in a URL using JavaScript?

前端 未结 19 2797
说谎
说谎 2020-11-22 02:10

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?

19条回答
  •  北荒
    北荒 (楼主)
    2020-11-22 02:32

    If the URI is not the document's location this snippet will do what you want.

    var url = 'example.com/page.html#anchor',
        hash = url.split('#')[1];
    
    if (hash) {
        alert(hash)
    } else {
        // do something else
    }
    

提交回复
热议问题