How to Check For a #Hash in a Url Using JavaScript

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

Simple use of location hash:

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

How to get #hash value in a URL in JS

function getHashValue(key) {
var matches = location.hash.match(new RegExp(key+'=([^&]*)'));
return matches ? matches[1] : null;
}

// usage
var hash = getHashValue('hash');

Check if url hash exists

Why not using directly location.hash

if(location.hash.length > 0) {
console.log('yep')
}else {
console.log('nop')
}

Detect the specific hash in URL

window.location.hash contains the # symbol. You can either include it on your comparison, or remove it from the variable hash.

Include the hash symbol:

if (hash === "#home")

Or remove the hash symbol:

var hash = "home"; // default 
if (window.location.hash.length > 0) {
hash = window.location.hash.substr(1);
}

How do you read a hash with an & sign in the URL?

You can do something like this:-

var hash = window.location.hash.substr(1);
var searchParams = new URLSearchParams(hash);
if(searchParams.has('id')) {
var id = searchParams.get('id');
console.log(id);
}

And same for other params if any. Hope this helps.



Related Topics



Leave a reply



Submit