我如何得到一个url的最后一段?我有下面的脚本,显示点击锚标记的完整url:
$(".tag_name_goes_here").live('click', function(event)
{
event.preventDefault();
alert($(this).attr("href"));
});
如果url为
http://mywebsite/folder/file
我如何才能让它在警告框中显示url的“文件”部分?
我如何得到一个url的最后一段?我有下面的脚本,显示点击锚标记的完整url:
$(".tag_name_goes_here").live('click', function(event)
{
event.preventDefault();
alert($(this).attr("href"));
});
如果url为
http://mywebsite/folder/file
我如何才能让它在警告框中显示url的“文件”部分?
当前回答
// 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);
其他回答
var urlChunks = 'mywebsite/folder/file'.split('/');
alert(urlChunks[urlChunks.length - 1]);
window.location.pathname.split("/").pop()
// 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);
仅使用javascript构建Frédéric的答案:
var url = document.URL
window.alert(url.substr(url.lastIndexOf('/') + 1));
获取当前窗口的最后一段:
window.location.href.substr(window.location.href.lastIndexOf('/') +1)