How do I find the last number in a URL, from left to right?
For example:
https://www.portal-gestao.com/introducao-6849.html
Would return: 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
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
.
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)
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
:
var myString = "https://www.portal-gestao.685com/introducao-6849.html";
var myRegexp = /(\d+)\D*$/g;
var match = myRegexp.exec(myString);
alert(match[1]);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.