javascript javascript如何切换window.location属性的路径名并重定向
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7757304/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
javascript how to switch pathname of window.location property and redirect
提问by Hcabnettek
I want to redirect a user from varying urls to a specific one. I've tried various flavors of replacing and I cant seem to get the behavior I want. This code works except I'm providing the hostname. I want to use the existing hostname from windows.location.hostname and just provide a new pathname. Sometimes the urls vary in size and slashes ('/').
我想将用户从不同的 URL 重定向到特定的 URL。我尝试了各种不同的替换方式,但似乎无法获得我想要的行为。除了我提供主机名外,此代码有效。我想使用 windows.location.hostname 中的现有主机名并只提供一个新的路径名。有时 url 的大小和斜线 ('/') 会有所不同。
window.location = 'http://localhost:36065/NewPath';
How would I change these urls?
我将如何更改这些网址?
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
I think you get the point. The path can vary in paths, I want to replace everything after .com basically with 'NewPath'
我认为你说对了。路径可能因路径而异,我想基本上用“NewPath”替换 .com 之后的所有内容
I'd like a clean regex solution if possible but I am quite the rookie in that dept. Thanks for any tips or tricks.
如果可能的话,我想要一个干净的正则表达式解决方案,但我是那个部门的菜鸟。感谢您提供任何提示或技巧。
回答by Jason Harwig
location.pathname = '/newpath.html'
回答by Alex Turpin
You could always use the various location
propertiesto recreate the part you need and append the new part to it:
您始终可以使用各种location
属性来重新创建您需要的部件并将新部件附加到它:
window.location = location.protocol + "//" + location.hostname + "/NewPath";
回答by Scott A
Just to show the hard way:
只是为了展示艰难的方式:
// 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, "/dir/foo/bar/newpage.html");