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

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

    Throwing this in here as a method for abstracting location properties from arbitrary URI-like strings. Although window.location instanceof Location is true, any attempt to invoke Location will tell you that it's an illegal constructor. You can still get to things like hash, query, protocol etc by setting your string as the href property of a DOM anchor element, which will then share all the address properties with window.location.

    Simplest way of doing this is:

    var a = document.createElement('a');
    a.href = string;
    
    string.hash;
    

    For convenience, I wrote a little library that utilises this to replace the native Location constructor with one that will take strings and produce window.location-like objects: Location.js

提交回复
热议问题