Replace current url with document.URL

13,847

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.

Share:
13,847
xhallix
Author by

xhallix

Updated on June 14, 2022

Comments

  • xhallix
    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
    xhallix about 11 years
    thank you, but this does not replace the whole URL, as I tried