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?
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: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: