Last segment of URL in jquery

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

    if the url is http://localhost/madukaonline/shop.php?shop=79

    console.log(location.search); will bring ?shop=79

    so the simplest way is to use location.search

    you can lookup for more info here and here

    0 讨论(0)
  • 2020-11-22 14:50
    var urlChunks = 'mywebsite/folder/file'.split('/');
    alert(urlChunks[urlChunks.length - 1]);
    
    0 讨论(0)
  • 2020-11-22 14:50

    I am using regex and split:

    var last_path = location.href.match(/./(.[\w])/)[1].split("#")[0].split("?")[0]

    In the end it will ignore # ? & / ending urls, which happens a lot. Example:

    https://cardsrealm.com/profile/cardsRealm -> Returns cardsRealm

    https://cardsrealm.com/profile/cardsRealm#hello -> Returns cardsRealm

    https://cardsrealm.com/profile/cardsRealm?hello -> Returns cardsRealm

    https://cardsrealm.com/profile/cardsRealm/ -> Returns cardsRealm

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

    I know it is old but if you want to get this from an URL you could simply use:

    document.location.pathname.substring(document.location.pathname.lastIndexOf('/.') + 1);
    

    document.location.pathname gets the pathname from the current URL. lastIndexOf get the index of the last occurrence of the following Regex, in our case is /.. The dot means any character, thus, it will not count if the / is the last character on the URL. substring will cut the string between two indexes.

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

    You can also use the lastIndexOf() function to locate the last occurrence of the / character in your URL, then the substring() function to return the substring starting from that location:

    console.log(this.href.substring(this.href.lastIndexOf('/') + 1));
    

    That way, you'll avoid creating an array containing all your URL segments, as split() does.

    0 讨论(0)
  • 2020-11-22 14:51
    window.location.pathname.split("/").pop()
    
    0 讨论(0)
提交回复
热议问题