Mr_Nizzle Mr_Nizzle - 1 year ago 42
Javascript Question

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

If I have the string:

var myStr = "foo_0_bar_0";


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


so if I do this:

myStr = getAndIncrementLastNumber(str); // "foo_0_bar_1"


Taking on considerations that there could be another text instead of
foo
and
bar
and there might not be
underscores
or there might be more than one
underscore
;

Is there any way with
JavaScript
or
jQuery
with
.replace()
and some
RegEx
?

Answer Source

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;
    });
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download