2011-10-13 80 views
5

我想将用户从不同的URL重定向到特定的URL。我尝试了各种口味的替代,我似乎无法得到我想要的行为。除了我提供主机名外,此代码可以工作。我想使用windows.location.hostname中的现有主机名,并提供一个新的路径名。有时这些网址的大小会有所不同('/')。javascript如何切换window.location属性的路径名并重定向

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'

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

回答

15
location.pathname = '/newpath.html' 
+0

+1,非常简单,为什么我没有想到这一点? –

+1

另外还有一个提示,它将哈希保存在URL中,但这可能不是问题。 –

+0

好点@ Xeon06,它也保留任何查询字符串 –

1

你总是可以使用the various location properties重新您需要的部分,并追加新的零件,将它:

+0

如果端口非标准(80,443)这不起作用 –

+0

确实。我可以添加它,但我认为@JasonHarwig有最好的解决方案。 –

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