How to get the URL anchor with Javascript
1 min read

How to get the URL anchor with Javascript

I tried to do something like a bookmark recently. I had a dynamically generated catalog and being like that, there were no separate URLs for each page, everything being handled by Javascript. So if you wanted to link someone with the page you were currently reading, all you could do was send him a link to the main URL where the first page would load. A nice way to enable someone to link directly to a page was to use anchors.

For example, if example.com/catalog.html were the address, one could go to the 10th page by using the example.com/catalog.html#10. Plain and simple and also not hard to remember.

The only thing that was left was to read that anchor, so you could tell the catalog to go directly to a certain page and skip the beginning. And this can easily be done with the following function:

function getAnchor() {
    var currentUrl = document.URL,
	urlParts   = currentUrl.split('#');
		
    return (urlParts.length > 1) ? urlParts[1] : null;
}

This line reads the current url and gets you example.com/catalog.html#10

var currentUrl = document.URL

After this, we split the currentUrl into an array where its parts are the bits of string separated by the character "#" (used for the anchor)

urlParts   = currentUrl.split('#');

urlParts should hold two elements: the main url, http://example.com/catalog.html and the anchor, 10.
So two is the minimum number of elements for an url with an anchor. If we didn't have any anchor, we would only have one elements. In order to be sure this is not the case and there is indeed an anchor, we check the urlParts array's length

(urlParts.length > 1) ? urlParts[1] : null;

So for the example just mentioned, calling getAnchor() would return 10 and if we were to use it on just http://example.com/catalog.html, without any anchor, it would return null.
Easy as pie!

Later edit (28.09.2012)

If you're looking for a shorter version of the code, for minification purposes, try this approach

function getAnchor() {
    return (document.URL.split('#').length > 1) ? document.URL.split('#')[1] : null;
}

It does exactly the same thing as before, the only difference being in the code lenght