javascript - 获取 URL 中的最后一个数字

标签 javascript jquery regex

如何从左到右查找 URL 中的最后一个数字?

例如:

https://www.portal-gestao.com/introducao-6849.html

将返回:6849

还有:

https://www.portal-gestao.com/curso-modelos-negocio/1452-introducao/6850-melhores-praticas-no-uso-de-folhas-de-calculo.html

将返回:6850

这就是我正在尝试的:

编辑:更新代码

jQuery('a.title').each(function () {
    var $link=jQuery(this);
    var href=$link.attr('href'); 
    var idx = href.indexOf('/')!=-1?1:0; // choose the second one if slash
    var procura=href.match(/(\d+)/g)[idx];

    jQuery.each(obj,function(_,test) {
        if(test.indexOf(procura)!=-1) { // only works on strings 
            ....
        }
    });
});

最佳答案

您可以使用正则表达式获取最后一个数字,如下所示。

function getLastNumber(url) {
    var matches = url.match(/\d+/g);
    return matches[matches.length - 1];
}

var url = 'https://www.portal-gestao.com/curso-modelos-negocio/1452-introducao/6850-melhores-praticas-no-uso-de-folhas-de-calculo.htm';
console.log(getLastNumber(url));

关于javascript - 获取 URL 中的最后一个数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35090936/

相关文章:

javascript - 对象中的函数和对 'this' 属性的访问 - 失败

javascript - 如何从 JavaScript 中的 fx 队列中删除 slideUp() slideDown()?

regex - Perl 正则表达式 : when to use $&

javascript - 时间轴 JScript 在 IExplorer 中不起作用

javascript - 使用 .hide() jquery 后 Div 重新出现

regex - 扩展 Cucumber 步骤

javascript - 使用 RegExp 构造函数导致错误的输出

javascript - jquery倒计时年月日

php - DIV 视频仅在第一次加载首页时显示

javascript - href 为 ="javascript:;"的 HTML <a> 元素的含义