admin管理员组文章数量:1279244
I have URLs like
or
Now I need to get only the url till dir3 and nothing after that… (or «everything till the sixth slash in the string»)
/
How can this be acblished with JavaScript?
I have URLs like
http://www.domain./dir/dir2/dir3/dir4/#tag
or
http://www.domain./dir/dir2/dir3/dir4
Now I need to get only the url till dir3 and nothing after that… (or «everything till the sixth slash in the string»)
http://www.domain./dir/dir2/dir3/
How can this be acblished with JavaScript?
Share Improve this question asked Jan 6, 2013 at 13:45 albuveealbuvee 2,7646 gold badges29 silver badges38 bronze badges2 Answers
Reset to default 7Try this:
'http://www.domain./dir/dir2/dir3/dir4/#tag'
.split('/')
.slice(0,6).join('/'));
//=> http://www.domain./dir/dir2/dir3
or a helper function:
function cutUrl(url,n){
return url.split('/').slice(0,n).join('/'));
}
You don't need jQuery here, JavaScript supports Regular Expression:
"http://www.domain./dir/dir2/dir3/dir4".match(/([^/]*\/){6}/)[0]
A safer way is(in case of pattern mismatched):
function cutUrl(str) {
var matched = str.match(/([^/]*\/){6}/);
return matched ? matched[0] : str/* or null if you wish */;
}
Then call cutUrl("http://www.domain./dir/dir2/dir3/dir4")
.
本文标签: jqueryJavaScript Cut URL after nth slashStack Overflow
版权声明:本文标题:jquery - JavaScript: Cut URL after nth slash - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741248069a2365267.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论