我如何得到一个url的最后一段?我有下面的脚本,显示点击锚标记的完整url:

$(".tag_name_goes_here").live('click', function(event)
{
    event.preventDefault();  
    alert($(this).attr("href"));
});

如果url为

http://mywebsite/folder/file

我如何才能让它在警告框中显示url的“文件”部分?


当前回答

一种避免查询参数的方法

const urlString = "https://stackoverflow.com/last-segment?param=123" const url =新的url (urlString); url。搜索= "; const lastSegment = url.pathname.split('/').pop(); console.log (lastSegment)

其他回答

Var部分= 'http://mywebsite/folder/file'.split('/'); var lastSegment = parts.pop() || parts.pop();//处理潜在的尾随斜杠 console.log (lastSegment);

我相信在执行substring之前删除尾部斜杠('/')会更安全。因为我的场景中有一个空字符串。

window.alert((window.location.pathname).replace(/\/$/, "").substr((window.location.pathname.replace(/\/$/, "")).lastIndexOf('/') + 1));

我知道,已经太迟了,但对于其他人来说: 我强烈推荐使用PURL jquery插件。PURL的动机是url也可以用“#”来分割(例如:angular.js links),即url可以看起来像

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

or

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

使用PURL,您可以很容易地决定(segment/fsegment)您想要获得的段。

对于“经典”的最后一部分,你可以这样写:

    var url = $.url('http://test.com/dir/index.html?key=value');
    var lastSegment = url.segment().pop(); // index.html

只是正则表达式的另一个解。

var href = location.href;
console.log(href.match(/([^\/]*)\/*$/)[1]);
// 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.substring(0,loc.length-1) : loc.substring(0,loc.lastIndexOf('/'));
var targetValue = loc.substring(loc.lastIndexOf('/') + 1);

targetValue = 1

如果你的url看起来像:

http://test.com/one/

or

http://test.com/one

or

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

然后loc最终看起来像: http://test.com/one

现在,因为您需要最后一项,所以运行下一步来加载最初需要的值(targetValue)。

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

// Store original location in loc like: http://test.com/one/ (ending slash) let loc = "http://test.com/one/index.htm"; console.log("starting loc value = " + loc); // If the last char is a slash trim it, otherwise return the original loc loc = loc.lastIndexOf('/') == (loc.length -1) ? loc.substring(0,loc.length-1) : loc.substring(0,loc.lastIndexOf('/')); let targetValue = loc.substring(loc.lastIndexOf('/') + 1); console.log("targetValue = " + targetValue); console.log("loc = " + loc);