2

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

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" Commented Mar 6, 2013 at 20:09
  • That's not what replace does. developer.mozilla.org/en-US/docs/JavaScript/Reference/… 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) 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. 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.com and you put document.location = "whatever", it will go to google.com/whatever, but if u put the entire URL: document.location = "http://www.whatever.com", only then it will replace the whole URL. Hope this helps. :) Commented Mar 6, 2013 at 20:22

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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

example

1 Comment

thank you, but this does not replace the whole URL, as I tried

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.