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

Viewed 207428

Example:

www.site.com/index.php#hello

Using jQuery, I want to put the value hello in a variable:

var type = …
8 Answers

Get fragment of current document location

var hash = window.location.hash;

Get fragment from string

// absolute
var url = new URL('https://example.com/path/index.html#hash');

console.log(url.hash);

// relative (second param is required, use any valid URL base)
var url2 = new URL('/path/index.html#hash2', 'http://example');

console.log(url2.hash);

Related