admin管理员组

文章数量:1279188

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

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

Share Improve this question edited Mar 6, 2013 at 20:03 Viktor S. 12.8k1 gold badge29 silver badges55 bronze badges asked Mar 6, 2013 at 20:01 xhallixxhallix 3,0115 gold badges40 silver badges57 bronze badges 12
  • 1 I'm sorry, but what are you trying to do? document.URL is equal to window.location.toString(), so your code will actually do document.location = "whatever" – Viktor S. Commented Mar 6, 2013 at 20:09
  • That's not what replace does. developer.mozilla/en-US/docs/JavaScript/Reference/… – SLaks Commented Mar 6, 2013 at 20:10
  • @FAngel: I'm trying to replace the whole URL. instead of putting them in replace as a string, I wanted to set the whole URL in var x. So I can change the URL even when it changes (e.g if a customer log in, the url changes) – xhallix Commented Mar 6, 2013 at 20:11
  • document.URL is a simple string. So I can change the URL even when it change - not clear what do you mean here. You can do that without any x var. – Viktor S. Commented Mar 6, 2013 at 20:14
  • If you put just a word or string in place of "whatever", it will just try to look for that file/path in the current location of where it is...for example: if u're on google. and you put document.location = "whatever", it will go to google./whatever, but if u put the entire URL: document.location = "http://www.whatever.", only then it will replace the whole URL. Hope this helps. :) – Chirag Bhatia - chirag64 Commented Mar 6, 2013 at 20:22
 |  Show 7 more ments

3 Answers 3

Reset to default 6

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 plete 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."

You should just use window.location.href = 'whatever'. Wouldn't that solve your problem?

window.location = 'whatever' works too, but it's technically inplete. Javascript will, however, implement it correctly.

May be window.location = 'whatever'; can help you?

example

本文标签: javascriptReplace current url with documentURLStack Overflow