Get and replace the last number on a string with JavaScript or jQuery

前端 未结 7 1552
挽巷
挽巷 2021-02-14 11:02

If I have the string:

var myStr = \"foo_0_bar_0\";

and I guess we should have a function called getAndIncrementLastNumber(str)

7条回答
  •  礼貌的吻别
    2021-02-14 11:11

    try this demo please http://jsfiddle.net/STrR6/1/ or http://jsfiddle.net/Mnsy3/

    code

    existingId = 'foo_0_bar_0';
    newIdOnly = existingId.replace(/foo_0_bar_(\d+)/g, "$1");
    alert(newIdOnly);
    
    getAndIncrementLastNumber(existingId);
    
    function getAndIncrementLastNumber(existingId){
        alert(existingId);
    newId = existingId.replace(/(\d+)/g, function(match, number) {
        return parseInt(number) + 1;
    });
    alert(newId);
    }
    ​
    

    or

       existingId = 'foo_0_bar_0';
    newIdOnly = existingId.replace(/foo_0_bar_(\d+)/g, "$1");
    alert(newIdOnly);
    
    getAndIncrementLastNumber(existingId);
    
    function getAndIncrementLastNumber(existingId){
        alert(existingId);
        newId = existingId.replace(/\d+$/g, function(number) {
        return parseInt(number) + 1;
    });
    alert("New ID ==> " + newId);
    }
    ​
    

提交回复
热议问题