Last segment of URL in jquery

前端 未结 26 941
说谎
说谎 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:34

    Or you could use a regular expression:

    alert(href.replace(/.*\//, ''));
    
    0 讨论(0)
  • 2020-11-22 14:34

    I believe it's safer to remove the tail slash('/') before doing substring. Because I got an empty string in my scenario.

    window.alert((window.location.pathname).replace(/\/$/, "").substr((window.location.pathname.replace(/\/$/, "")).lastIndexOf('/') + 1));
    
    0 讨论(0)
  • 2020-11-22 14:36

    Javascript has the function split associated to string object that can help you:

    var url = "http://mywebsite/folder/file";
    var array = url.split('/');
    
    var lastsegment = array[array.length-1];
    
    0 讨论(0)
  • 2020-11-22 14:38

    If you aren't worried about generating the extra elements using the split then filter could handle the issue you mention of the trailing slash (Assuming you have browser support for filter).

    url.split('/').filter(function (s) { return !!s }).pop()
    
    0 讨论(0)
  • 2020-11-22 14:41

    you can first remove if there is / at the end and then get last part of url

    let locationLastPart = window.location.pathname
    if (locationLastPart.substring(locationLastPart.length-1) == "/") {
      locationLastPart = locationLastPart.substring(0, locationLastPart.length-1);
    }
    locationLastPart = locationLastPart.substr(locationLastPart.lastIndexOf('/') + 1);
    
    0 讨论(0)
  • 2020-11-22 14:41

    You can do this with simple paths (w/0) querystrings etc.

    Granted probably overly complex and probably not performant, but I wanted to use reduce for the fun of it.

      "/foo/bar/"
        .split(path.sep)
        .filter(x => x !== "")
        .reduce((_, part, i, arr) => {
          if (i == arr.length - 1) return part;
        }, "");
    
    1. Split the string on path separators.
    2. Filter out empty string path parts (this could happen with trailing slash in path).
    3. Reduce the array of path parts to the last one.
    0 讨论(0)
提交回复
热议问题