9

我想将用户从不同的 url 重定向到特定的。我尝试了各种替换方式,但似乎无法获得我想要的行为。除了我提供主机名外,此代码有效。我想使用 windows.location.hostname 中的现有主机名,只需提供一个新的路径名。有时 url 的大小和斜杠 ('/') 会有所不同。

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

我认为你说对了。路径可能会有所不同,我想将 .com 之后的所有内容基本上替换为“NewPath”

如果可能的话,我想要一个干净的正则表达式解决方案,但我是那个部门的新手。感谢您提供任何提示或技巧。

4

3 回答 3

25
location.pathname = '/newpath.html'
于 2011-10-13T16:35:30.703 回答
4

您始终可以使用各种location属性来重新创建您需要的部分并将新部分附加到它:

window.location = location.protocol + "//" + location.hostname + "/NewPath";
于 2011-10-13T16:35:01.633 回答
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");
于 2011-10-13T17:06:48.543 回答