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
Create a Date With a Set Timezone Without Using a String Representation
How to Remove Item from Array by Value
JavaScript - Track Mouse Position
Is "Clear" a Reserved Word in JavaScript
Programmatically Changing Webkit-Transformation Values in Animation Rules
Serving Gzipped CSS and JavaScript from Amazon Cloudfront via S3
How to Use JavaScript to Check and Load CSS If Not Loaded
Jquery Live Scroll Event on Mobile (Work Around)
Dynamically Load a JavaScript File
Rotate the Elements in an Array in JavaScript
How to Check If File Exists in Jquery or Pure JavaScript
Tainted Canvases May Not Be Exported
Curly Brackets in Arrow Functions
Add Inline Style Using JavaScript