Get specific part of url of a link

后端 未结 4 1102
耶瑟儿~
耶瑟儿~ 2021-01-17 02:40

I want to get a specific part of a url between the third and fourth slashes of a link on the page.

EDIT: Sorry I don\'t think I was clear the first time, I meant get

相关标签:
4条回答
  • 2021-01-17 02:56
    var getSegment = function (url, index) {
       return url.replace(/^https?:\/\//, '').split('/')[index];
    }
    

    Usage:

    getSegment("http://domain.com/a/b/c/d/e", 4); // "d" 
    

    The replace makes sure that the first two slashes after the protocol (http or https) don't count.

    0 讨论(0)
  • 2021-01-17 03:02

    Here's a working example of getting a particular path segment.

    Code:

    var url = "www.test.com/one/two/three?p1=v&p2=v#anc";
    var file = url.split('?')[0];
    var pathanddomain = file.split('/');
    var path = pathanddomain.splice(1, pathanddomain.length-1);
    var pathIndexToGet = 2;
    document.write(path[pathIndexToGet]);​
    

    If you want to do this for the current page, use:

    var url = window.location.href;
    

    Also, if your url starts with http(s)://, you will need to remove this.

    0 讨论(0)
  • 2021-01-17 03:09

    I'd suggest:

    var link = 'http://www.example.com/directory1/directory2/directory3/directory4/index.html';
    
    console.log(link.split('/')[5]);​
    

    JS Fiddle demo.

    The reason we're using [5] not [4] is because of the two slashes at the beginning of the URL, and because JavaScript arrays are zero-based.

    0 讨论(0)
  • 2021-01-17 03:17

    you should elaborate you question and should specify which is your domain, that means on what purpose you are asking that question ??

    This may help you:

    var urlValue = url.split("/");
    

    Then store urlValue as array. then pick up third and forth value of the urlvalue on array.

    0 讨论(0)
提交回复
热议问题