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

前端 未结 7 1573
挽巷
挽巷 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:26

    Here's how I do it:

    function getAndIncrementLastNumber(str) {
        return str.replace(/\d+$/, function(s) {
            return ++s;
        });
    }
    

    Fiddle

    Or also this, special thanks to Eric:

    function getAndIncrementLastNumber(str) {
        return str.replace(/\d+$/, function(s) {
            return +s+1;
        });
    }
    

    Fiddle

提交回复
热议问题