Last segment of URL in jquery

前端 未结 26 1484
说谎
说谎 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);
    

提交回复
热议问题