Last segment of URL in jquery

前端 未结 26 1387
说谎
说谎 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: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).

提交回复
热议问题