Explain Codes LogoExplain Codes Logo

How do I get the fragment identifier (value after hash #) from a URL?

javascript
prompt-engineering
functions
callbacks
Anton ShumikhinbyAnton Shumikhin·Feb 12, 2025
TLDR

Grab the URL fragment identifier using window.location.hash in JavaScript, then smartly discard the hash # with .slice(1):

let fragment = window.location.hash.slice(1);

This hands you the clean fragment string for your further adventures.

Beyond the Basics

Sometimes, you'll cross paths with solutions which need a little more finesse. These challenges could spring from a URL in string format, the need for backward compatibility, or dealing with non-standard contexts such as href attributes.

Digging through Strings

If you need to extract the fragment from a URL string, rather than directly from window.location, you can do it using this neat trick:

let url = "https://example.com/page#gold"; let fragment = url.substring(url.indexOf('#') + 1);

It's the ol' find-and-chop: locate the #, slice everything after. Easy as apple pie!

Bulletproofing Your Code

What if the hash isn't there? Here's where if is our digital armor:

if(window.location.hash) { let fragment = window.location.hash.slice(1); // Carry on, wayward coder } else { // Nothing to see here, move along }

Taming Wild Characters

You might come across URLs with special, escaped characters. window.location.hash decodes these automatically. If you want the raw, untouched hash, try this approach instead:

let fullURL = window.location.href; let rawFragment = fullURL.includes('#') ? fullURL.split('#')[1] : ''; // Raw, organic, free-range fragment. None of that GMO stuff here.

Dancing with Hashed Routes

In the world of Single Page Applications (SPA), hash routing is the talk of the town. In these instances, it's crucial to listen to the beat and move with the rhythm of hash changes:

window.addEventListener('hashchange', function() { let currentHash = window.location.hash.slice(1); // The hash changed. Time to strut your stuff! });

This party trick ensures your JavaScript always catches the latest goss and responds to changes appropriately.

Staying lightweight with pure JavaScript

We all love a bit of jQuery, but why bring a chainsaw to a knife fight? For something as brief as yanking a URL fragment, pure JavaScript steals the show:

let fragment = window.location.hash.slice(1); // Hey look, Ma! No libraries!

Test Drives

Online playgrounds like jsfiddle or CodePen are great sandboxes to play around with URL manipulations. Test your logic, break stuff, fix it - all without causing an actual apocalypse!