Search code examples
javascripturlgetwindowanchor

Javascript: document.url without the anchor (hash) portion


I've tried searching for this for 30 minutes, so I apologize if it's been asked already.

I have some Ajax which returns a set of results and when one is clicked it simply reloads the URL with the appended data to the URL for PHP to GET on the next page. The problem is, if the user clicked to some built in anchoring (which I cannot remove), the URL will be something.com#location1 so appending ?action=next will turn it into something.com#location1?action=next which the browser interprets as a long anchor, rather than a new URL to actually direct to.

If the user never clicks the anchor portion this redirect works smoothly using window.location=document.url+"?action=next"

Is there a way to remove the anchor (including the hash tag) from the existing page's URL?

SOLVED

Using Michael W's answer I was able to solve it. I simply replaced this line:

window.location=document.url+"?action=next"

With this:

window.location=document.location.href.match(/(^[^#]*)/)[0]+"?action=next"

Thanks for the help!


Solution

  • You could match for the pre-hashtag portion of the location:

    document.location.href.match(/(^[^#]*)/)