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 badges
Add a ment  | 

2 Answers 2

Reset to default 7

Try 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