Search code examples
javascripturlhashanalytics

Javascript - Check for Hash, Ignore Analytics Code following


We are adding a video to the home page of a site, and want to be able to automatically pop up the video (in a lightbox-style container) whenever the #video tag is present in the URL:

http://www.domain.com#video

The video needs to pop up if a link is clicked internally on the site (ie: <a href="#video">) and also if the hash is present in the URL on page load.

Easy enough to check for the hash in the URL using window.location.hash or when a link with the hash is clicked and fire the associated javascript function. That's working as expected without any issues.

However as this URL will be sent out in emails with Google Analytics code automatically added, the analytics code is appended to the end of the URL:

http://www.domain.com#video?utm_source=...

Because the analytics code will change with each email campaign, I can't do a simple Javascript replace() to ignore the analytics code.

How do I go about checking whether the hash is present in the URL, but ignore anything after a ? if present?


Solution

  • Isn't the proper form of a URL to have the hash at the end after the query parameters? Then, the location.hash variable will work properly and you won't need special code. Your URL should look like this and then you can just directly use location.hash which will be #video:

    http://www.domain.com?utm_source=xxx#video

    I don't advise this as the solution (I think you ought to get the URLs fixed to be legal), but you can use this code to parse the hash value out of the URL even if it's in the illegal position:

    var matches = window.location.href.match(/#(.*?)(\?|$)/);
    if (matches) {
        var hash = matches[1];
    }
    

    This code extracts from the "#" to either end of string or "?" whichever comes first. You can see it run on a bunch of test URLs here: http://jsfiddle.net/jfriend00/HuqL7/.