Last segment of URL in jquery

前端 未结 26 940
说谎
说谎 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:28
    window.alert(this.pathname.substr(this.pathname.lastIndexOf('/') + 1));
    

    Use the native pathname property because it's simplest and has already been parsed and resolved by the browser. $(this).attr("href") can return values like ../.. which would not give you the correct result.

    If you need to keep the search and hash (e.g. foo?bar#baz from http://quux.com/path/to/foo?bar#baz) use this:

    window.alert(this.pathname.substr(this.pathname.lastIndexOf('/') + 1) + this.search + this.hash);
    
    0 讨论(0)
  • 2020-11-22 14:31

    To get the last segment of your current window:

    window.location.href.substr(window.location.href.lastIndexOf('/') +1)

    0 讨论(0)
  • 2020-11-22 14:31
    // https://x.com/boo/?q=foo&s=bar = boo
    // https://x.com/boo?q=foo&s=bar = boo
    // https://x.com/boo/ = boo
    // https://x.com/boo = boo
    
    const segment = new 
    URL(window.location.href).pathname.split('/').filter(Boolean).pop();
    console.log(segment);
    

    Works for me.

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

    I know, it is too late, but for others: I highly recommended use PURL jquery plugin. Motivation for PURL is that url can be segmented by '#' too (example: angular.js links), i.e. url could looks like

        http://test.com/#/about/us/
    

    or

        http://test.com/#sky=blue&grass=green
    

    And with PURL you can easy decide (segment/fsegment) which segment you want to get.

    For "classic" last segment you could write:

        var url = $.url('http://test.com/dir/index.html?key=value');
        var lastSegment = url.segment().pop(); // index.html
    
    0 讨论(0)
  • 2020-11-22 14:33
    var pathname = window.location.pathname; // Returns path only
    var url      = window.location.href;     // Returns full URL
    

    Copied from this answer

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

    var parts = 'http://mywebsite/folder/file'.split('/');
    var lastSegment = parts.pop() || parts.pop();  // handle potential trailing slash
    
    console.log(lastSegment);

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