JavaScript如何切换window.location属性的路径并重定向?

11

我想要将用户从不同的网址重定向到一个特定的网址。我尝试过各种替换方式,但似乎无法得到我想要的行为。这段代码可以工作,但是我提供了主机名。我想使用来自windows.location.hostname的现有主机名,只提供新路径名。有时网址的长度和斜杠 ('/') 会有所不同。

window.location = 'http://localhost:36065/NewPath';

我该如何更改这些网址?

http://somesite.com/xxx/yyy/zzz to http://somesite.com/NewPath
http://somesite.com/xxx/yyy to http://somesite.com/NewPath
http://somesite.com/xxx to http://somesite.com/NewPath

我想你已经理解了重点。路径可能会有所变化,我想基本上用 'NewPath' 替换 .com 后面的所有内容。

如果可能的话,我希望有一个简洁的正则表达式解决方案,但在这方面我是个新手。谢谢任何提示或技巧。

3个回答

31
location.pathname = '/newpath.html'

1
还有一点需要注意的是,这会在URL中保留哈希值,但这可能不是问题。 - Alex Turpin
不太确定我怎么会错过这个。如此简单。谢谢! - Hcabnettek
通过设置 pathname 属性,您可以保留查询参数和片段标识符。@vsync - Jason Harwig
@JasonHarwig - 我刚试着更改路径名,但是没有保留查询参数.. (FF30/WIN7) - vsync
有没有办法更改路径名以使浏览器不会“加载”新的路径名?我知道有pushState()但是我正在尝试有效地从浏览器历史记录中删除最近的URL,而pushState()并不能做到这一点。 - user1063287
@user1063287 我相信History.replaceState()方法会对此有所帮助。 - Anthony Walsh

4
您可以始终使用各种location属性来重新创建所需的部分,并将新部分附加到其中:
window.location = location.protocol + "//" + location.hostname + "/NewPath";

1
确实。我可以添加它,但我认为@JasonHarwig有最好的解决方案。 - Alex Turpin
这里缺少端口,可能还有哈希和搜索字段。Location.origin 可能会有所帮助。 - ARDVL

0

只是展示困难的方法:

// Find everything up to the first slash and save it in a backreference
regexp = /(\w+:\/\/[^\/]+)\/.*/;

// Replace the href with the backreference and the new uri
newurl = windows.location.href.replace(regexp, "$1/dir/foo/bar/newpage.html");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接