Site icon Denis Bouquet

How to get the URL hash only, without other extra parameters in JavaScript?

It might happen that you use the hash of a URL to jump to a section of a webpage, or bypass some steps in a quiz/tool, etc. Here is a solution using window.location.hash.split(‘?’)[0];

How to get only the hash parameters of a URL?

If you post on social media, the original URL shared gets extra parameters added at the end for tracking purposes.

Let’s imagine I am sharing the link www.mywebsite.com#chapter3 on Instagram, the URL published becomes something like www.mywebsite.com#chapter3?utm_medium=social&utm_source=igMyWebsite&utm_content=2023-11-13T15%3A23%3A01

In that case, window.location.hash is not equal to “#chapter3” but to “#chapter3?utm_medium=social&utm_source=igMyWebsite&utm_content=2023-11-13T15%3A23%3A01

This can cause issues if you use the hash to navigate or bypass sections of the website; window.location.hash

Solution

Using .split(‘?’) is the solution to retain only the hash part; window.location.hash.split(‘?’)[0]

The split() method splits a string into an array of substrings. It returns the new array. If the separator parameter is not part of the string, an array with the original string is returned.

string.split(separator, limit)

In our case, the first entry in the array [0] will be either the full string or the part of the URL before the special character “?”.

if(window.location.hash) {
    // Fragment exists, get only the anchor part
    const hash = window.location.hash.split('?')[0];

    if($(hash).length > 0) {
        // do what you need there
        if($('a[href="'+hash+'"]').length > 0) {	
            // chapter selected
            $('a[href="'+hash+'"]').eq(0).trigger('click');
        }
    }
}

Please note that the example above uses the $ of jQuery. Adapt for your own needs.

Hope this helps someone!

Exit mobile version