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

前端 未结 7 1534
挽巷
挽巷 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:18

    You can use the regular expression /[0-9]+(?!.*[0-9])/ to find the last number in a string (source: http://frightanic.wordpress.com/2007/06/08/regex-match-last-occurrence/). This function, using that regex with match(), parseInt() and replace(), should do what you need:

    function increment_last(v) {
        return v.replace(/[0-9]+(?!.*[0-9])/, parseInt(v.match(/[0-9]+(?!.*[0-9])/), 10)+1);
    }
    

    Probably not terribly efficient, but for short strings, it shouldn't matter.

    EDIT: Here's a slightly better way, using a callback function instead of searching the string twice:

    function increment_last(v) {
        return v.replace(/[0-9]+(?!.*[0-9])/, function(match) {
            return parseInt(match, 10)+1;
        });
    }
    

提交回复
热议问题