Last segment of URL in jquery

前端 未结 26 943
说谎
说谎 2020-11-22 13:47

How do I get the last segment of a url? I have the following script which displays the full url of the anchor tag clicked:

$(\".tag_name_goes_here\").live(\         


        
相关标签:
26条回答
  • 2020-11-22 14:42

    Returns the last segment, regardless of trailing slashes:

    var val = 'http://mywebsite/folder/file//'.split('/').filter(Boolean).pop();
    
    console.log(val);

    0 讨论(0)
  • 2020-11-22 14:43

    The other answers may work if the path is simple, consisting only of simple path elements. But when it contains query params as well, they break.

    Better use URL object for this instead to get a more robust solution. It is a parsed interpretation of the present URL:

    Input: const href = 'https://stackoverflow.com/boo?q=foo&s=bar'

    const segments = new URL(href).pathname.split('/');
    const last = segments.pop() || segments.pop(); // Handle potential trailing slash
    console.log(last);
    

    Output: 'boo'

    This works for all common browsers. Only our dying IE doesn't support that (and won't). For IE there is a polyfills available, though (if you care at all).

    0 讨论(0)
  • 2020-11-22 14:45

    Just another solution with regex.

    var href = location.href;
    console.log(href.match(/([^\/]*)\/*$/)[1]);
    
    0 讨论(0)
  • 2020-11-22 14:46
    // Store original location in loc like: http://test.com/one/ (ending slash)
    var loc = location.href; 
    // If the last char is a slash trim it, otherwise return the original loc
    loc = loc.lastIndexOf('/') == (loc.length -1) ? loc.substr(0,loc.length-1) : loc.substr(0,loc.lastIndexOf('/'));
    var targetValue = loc.substr(loc.lastIndexOf('/') + 1);
    

    targetValue = one

    If your url looks like:

    http://test.com/one/

    or

    http://test.com/one

    or

    http://test.com/one/index.htm

    Then loc ends up looking like: http://test.com/one

    Now, since you want the last item, run the next step to load the value (targetValue) you originally wanted.

    var targetValue = loc.substr(loc.lastIndexOf('/') + 1);
    
    0 讨论(0)
  • 2020-11-22 14:48

    Building on Frédéric's answer using only javascript:

    var url = document.URL
    
    window.alert(url.substr(url.lastIndexOf('/') + 1));
    
    0 讨论(0)
  • 2020-11-22 14:48

    I don't really know if regex is the right way to solve this issue as it can really affect efficiency of your code, but the below regex will help you fetch the last segment and it will still give you the last segment even if the URL is followed by an empty /. The regex that I came up with is:

    [^\/]+[\/]?$
    
    0 讨论(0)
提交回复
热议问题