Monday, May 1, 2017

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

if we are using ajax and on the response we want to know the url has # or not. so by this code we can find it it have the # on the url or not.


Method 1:-
if(window.location.hash) {
  // Fragment exists
} else {
  // Fragment doesn't exist
}


Method 2:-
if (location.href.indexOf("#") != -1) {
        // Your code in here accessing the string like this
        // location.href.substr(location.href.indexOf("#"))
    }


Method 3:-

var url = 'example.com/page.html#anchor',
    hash = url.split('#')[1];

if (hash) {
    alert(hash)
} else {
    // do something else
}

Method 4:-
  
var requestedHash = ((window.location.hash.substring(1).split("#",1))+"?").split("?",1);

No comments:

Post a Comment