2012-01-27 41 views
0

我有这个URL http://www.something.com/categoryjavascript:找到字符串内的字符串的第二个最后的外观?

top.location.href.substr(0, top.location.href.lastIndexOf("/")); 

回报http://www.something.com

但是,如果我有URL http://www.something.com/category/something我怎么能再次通过去除 “/” ...

任何二号最后一个出场检索http://www.something.com理念?我知道有像top.location.origin这样的东西。我需要一种方法来削减最后两个“斜线”!

+0

当下一个URL出现在'www.something.com/category/something/things /'时,那么是什么?我相信你的问题是如何获得没有路径的网址。 – TJHeuvel 2012-01-27 15:30:54

+0

'var foo = url.split('/',3).join('/');' – Yoshi 2012-01-27 15:33:23

+0

你想分析一个通用的URL,或者你打算使用window.location对象吗? – zzzzBov 2012-01-27 15:33:29

回答

1

既然你与location对象,利用工作:

location.protocol + '//' + location.host + '/'; 
// On this page, it shows: http://stackoverflow.com/ 
// Include pathname: 
location.protocol + '//' + location.host + location.pathname + '/'; 

对于自己的解决方案,你可以添加+1的第二个参数:

top.location.href.substr(0, top.location.href.lastIndexOf("/")+1); 
                   ^^ Hi Plus One! 

应对更新的问题(见OP的评论):

var href = top.location.href.replace(/(\/[^\/]+){2}\/?$/, ''); 
+0

@OP - docs是你的朋友=)。 https://developer.mozilla.org/en/DOM/window.location – mrtsherman 2012-01-27 15:34:20

0

而不是倒退哪个c有一个可变数量的索引,为什么不前进,你知道只有2个索引?

var url = top.location.href; 
var index1 = url.indexOf('/'); 
var index3 = url.indexOf('/', index1 + 2); 
var final = url.substr(0, index3); 
相关问题