用document.URL替换当前url

时间:2013-03-06 20:01:36

标签: javascript url replace window.location

我试图获取当前网址并将其替换为其他内容。 但是如果x = document.URL我的代码不起作用,但对于x =“String”,一切都运行良好

function test(){

    var x = document.URL    
    var url = window.location.toString();
    window.location = url.replace( x , 'whatever');
}
test();

感谢您帮助我

3 个答案:

答案 0 :(得分:4)

变量urlx的值是相同的,因此您只需将整个网址替换为'what'即可。为什么不直接使用window.location = 'whatever'

如果您想要替换整个网址,则需要在放置whatever的字符串中提供完整的网址,否则它将作为相对网址而不是绝对网址。

请尝试window.location = "http://www.google.com"

之类的内容

答案 1 :(得分:1)

您应该使用window.location.href = 'whatever'。这不会解决你的问题吗?

window.location = 'whatever'也有效,但技术上不完整。但是,Javascript会正确实现它。

答案 2 :(得分:0)

可能window.location = 'whatever';可以帮到你吗?

example