简体   繁体   English

获取URL中的最后一个数字

[英]Get the last number in a URL

How do I find the last number in a URL, from left to right? 如何从左到右找到URL中的最后一个数字?

For example: 例如:

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

Would return: 6849 将返回: 6849

And: 和:

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

Would return: 6850 将返回: 6850

This is what I'm trying: 这就是我正在尝试的:

EDIT: Updated code 编辑:更新的代码

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 
            ....
        }
    });
});

You can get the last number like following using regex . 您可以使用regex获取最后一个数字,如下所示。

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));

Here's a general solution that would give you the last number in a string (not necessarily a URL) 这是一个通用的解决方案,可以为您提供字符串中的最后一个数字(不一定是URL)

function getLastNumberOfString(str){
  var allNumbers = str.replace(/[^0-9]/g, ' ').trim().split(/\s+/);
  return parseInt(allNumbers[allNumbers.length - 1], 10);
}

This regex should do the job, it gets you the last number in the myString : 这个正则表达式应该完成这项工作,它会让你获得myString的最后一个数字:

var myString = "https://www.portal-gestao.685com/introducao-6849.html";
var myRegexp = /(\d+)\D*$/g;
var match = myRegexp.exec(myString);
alert(match[1]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM