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

前端 未结 19 3260
说谎
说谎 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:24

    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.

提交回复
热议问题