繁体   English   中英

javascript如何切换window.location属性的路径名和重定向

[英]javascript how to switch pathname of window.location property and redirect

我想将用户从不同的URL重定向到特定的URL。 我尝试了各种各样的替换方式,似乎无法得到我想要的行为。 除了我提供主机名外,此代码有效。 我想使用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

我认为你说对了。 路径可以在路径上变化,我想在.com之后基本上用'NewPath'替换所有内容

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

location.pathname = '/newpath.html'

您始终可以使用各种location属性来重新创建所需的零件,并将新零件附加到其中:

window.location = location.protocol + "//" + location.hostname + "/NewPath";

只是为了表明困难的方式:

// 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");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM