Saturday, 1 February 2014

Replacing Question Mark in URL With Javascript

First published on adamalton.co.uk on 29th March 2010.

This seemingly simple task caught me out slightly the other day.  The usual trip to Google was surprisingly un-helpful.  And then I had an important realisation... document.location.replace(/regex/, 'replacement') IS NOT THE SAME AS String(document.location).replace(/regex/, 'replacement') document.location is an object, which has a method called 'replace', which reloads the page with the given url string.  Which of course is totally different to the Javascript String object's 'replace' method.

As for replacing the question mark (I was trying to find the URL of the current page up to the query string), it just needs escaping with a backslash, which is what you'd expect with a regular expression.  Once you stop being a plank and you turn the url into a String before calling .replace() on it, it all works fine. url_without_query_string = String(document.location).replace(/(#|\?).*/, '')





1 comment: