簡體   English   中英

獲取URL中的最后一個數字

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM