Last segment of URL in jquery

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

    // Store original location in loc like: http://test.com/one/ (ending slash)
    var loc = location.href; 
    // If the last char is a slash trim it, otherwise return the original loc
    loc = loc.lastIndexOf('/') == (loc.length -1) ? loc.substr(0,loc.length-1) : loc.substr(0,loc.lastIndexOf('/'));
    var targetValue = loc.substr(loc.lastIndexOf('/') + 1);
    

    targetValue = one

    If your url looks like:

    http://test.com/one/

    or

    http://test.com/one

    or

    http://test.com/one/index.htm

    Then loc ends up looking like: http://test.com/one

    Now, since you want the last item, run the next step to load the value (targetValue) you originally wanted.

    var targetValue = loc.substr(loc.lastIndexOf('/') + 1);
    

提交回复
热议问题