Replace current url with document.URL
Solution 1
The values of the variables url
and x
are the same, so you're simply replacing the whole URL with 'whatever'. Why not just use window.location = 'whatever'
instead?
If you want the whole URL to be replaced, you need to give a complete URL in the string where you've put whatever
, otherwise it will act as a relative URL instead of an absolute one.
So try something like window.location = "http://www.google.com"
Solution 2
You should just use window.location.href = 'whatever'
. Wouldn't that solve your problem?
window.location = 'whatever'
works too, but it's technically incomplete. Javascript will, however, implement it correctly.
xhallix
Updated on June 14, 2022Comments
-
xhallix almost 2 years
I was trying to get the current URL and replace it with something else. But my code does not work if x = document.URL, but for x = "String" everything works perfectly
function test(){ var x = document.URL var url = window.location.toString(); window.location = url.replace( x , 'whatever'); } test();
Thank you for helping me out
-
xhallix about 11 yearsthank you, but this does not replace the whole URL, as I tried