If I have the string:
var myStr = \"foo_0_bar_0\";
and I guess we should have a function called getAndIncrementLastNumber(str)
@Brilliant is right, +1, I just wanted to provide a version of his answer with 2 modifications:
negative look-ahead
operator.```
/**
* Increments the last integer number in the string. Optionally adds a number to it
* @param {string} str The string
* @param {boolean} addIfNoNumber Whether or not it should add a number in case the provided string has no number at the end
*/
function incrementLast(str, addIfNoNumber) {
if (str === null || str === undefined) throw Error('Argument \'str\' should be null or undefined');
const regex = /[0-9]+$/;
if (str.match(regex)) {
return str.replace(regex, (match) => {
return parseInt(match, 10) + 1;
});
}
return addIfNoNumber ? str + 1 : str;
}
Tests:
describe('incrementLast', () => {
it('When 0', () => {
assert.equal(incrementLast('something0'), 'something1');
});
it('When number with one digit', () => {
assert.equal(incrementLast('something9'), 'something10');
});
it('When big number', () => {
assert.equal(incrementLast('something9999'), 'something10000');
});
it('When number in the number', () => {
assert.equal(incrementLast('1some2thing9999'), '1some2thing10000');
});
it('When no number', () => {
assert.equal(incrementLast('1some2thing'), '1some2thing');
});
it('When no number padding addIfNoNumber', () => {
assert.equal(incrementLast('1some2thing', true), '1some2thing1');
});
});