将当前 url 替换为 document.URL

xha*_*lix 2 javascript url replace window.location

我试图获取当前的 URL 并将其替换为其他内容。但如果 x = document.URL,我的代码不起作用,但对于 x = "String" 一切正常

function test(){

    var x = document.URL    
    var url = window.location.toString();
    window.location = url.replace( x , 'whatever');
}
test();
Run Code Online (Sandbox Code Playgroud)

谢谢你帮助我

Chi*_*g64 5

变量url和的值x是相同的,因此您只需将整个 URL 替换为“whatever”即可。为什么不直接使用window.location = 'whatever'呢?

如果要替换整个 URL,则需要在放置的字符串中给出完整的 URL whatever,否则它将充当相对 URL,而不是绝对 URL。

所以尝试类似的东西window.location = "http://www.google.com"