How to get #hash value in a URL in JS

Viewed 40729
7 Answers

The URLSearchParams class can be reused for this purpose.

var urlParams = new URLSearchParams(window.location.hash.replace("#","?"));
var hash = urlParams.get('hash');

If url has ?: http://www.google.com/#?hash=value2x

The code can be:

const url = 'http://www.google.com/#?hash=value2x';
new URLSearchParams(
  (
    new URL(url)
  ).hash.slice(1).split('?')[1]
).get('hash');

Or if url has no ?:

const url = 'http://www.google.com/#hash=value2x';
(new URLSearchParams((new URL(url)).hash.slice(1))).get('hash')
Related