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

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

如果url为

http://mywebsite/folder/file

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


当前回答

使用RegEx获取最后一段

str.replace(/.*\/(\w+)\/?$/, '$1');

$1表示使用捕获组。使用RegEx (\w+)创建第一个组,然后将整个字符串替换为捕获组。

let str =“http://mywebsite/folder/ fill”; 让我们把它放在一起。$ / ' $ '); 游戏机。log (lastSegment);

其他回答

或者你可以使用正则表达式:

alert(href.replace(/.*\//, ''));

返回最后一段,不考虑后面的斜杠:

瓦尔瓦尔= http://mywebsite/folder/file//’。分裂(' / ')。布尔(过滤器)pop (); 控制台日志(val);

Javascript有与字符串对象相关联的函数split,可以帮助你:

const url = "http://mywebsite/folder/file";
const array = url.split('/');

const lastsegment = array[array.length-1];

获取URL最后一段删除(-)和(/)的最佳方法

 jQuery(document).ready(function(){
        var path = window.location.pathname;
        var parts = path.split('/');
        var lastSegment = parts.pop() || parts.pop();  // handle potential trailing slash
        lastSegment = lastSegment.replace('-',' ').replace('-',' ');
        jQuery('.archive .filters').before('<div class="product_heading"><h3>Best '+lastSegment+' Deals </h3></div>');
    
    }); 

获取当前窗口的最后一段:

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