[英]Get the last number in a URL
如何从左到右找到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
....
}
});
});
您可以使用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));
这是一个通用的解决方案,可以为您提供字符串中的最后一个数字(不一定是URL)
function getLastNumberOfString(str){
var allNumbers = str.replace(/[^0-9]/g, ' ').trim().split(/\s+/);
return parseInt(allNumbers[allNumbers.length - 1], 10);
}
这个正则表达式应该完成这项工作,它会让你获得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.