Creating a new Location object in javascript

Well, you could use an anchor element to extract the url parts, for example:

var url = document.createElement('a');
url.href = "http://www.example.com/some/path?name=value#anchor";
var protocol = url.protocol;
var hash = url.hash;

alert('protocol: ' + protocol);
alert('hash: ' + hash);
​

It works on all modern browsers and even on IE 5.5+.

Check an example here.


How about use the standard URL object?

const url = new URL("http://www.example.com/some/path?name=value#anchor");
const { hash } = url;

Then console.log(hash) will output #anchor.

Warning: This interface is a bit new, so, if you're not using a transpiler, please, check the compatibility table and do your tests at target browsers.


You can leverage the power of an anchor element

var aLink = document.createElement("a");
aLink.href="http://www.example.com/foo/bar.html?q=123#asdf";
alert(aLink.pathname);