Andrew Andrew - 3 months ago 9
Javascript Question

Is there a way to pass a URL with a hash in it to a javascript variable?

if I have a URL of www.google.co.uk/test#number1 is there a way to pass the

window.location.pathname;

to a variable to read as
test#number1
rather than the variable terminating at the "#" hash symbol?

Thanks in advance.

EDIT (with more info).

What I was looking to achieve is populating a text box with the pathname of the current URL that contains hashes.

riscarrott's answer works perfectly but because I have <15 rep I can't up vote it. :(

document.getElementById("textbox").innerHTML =
window.location.pathname + window.location.hash;

Answer

You can read the hash on the location object too:

// https://www.google.co.uk/test#number1
var foo = window.location.pathname + window.location.hash;
console.log(foo) // "/test#number1"

MDN provides good documentation on the BOM -- https://developer.mozilla.org/en-US/docs/Web/API/Window/location