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
?
Use the String. replace() method to replace the last character in a string, e.g. const replaced = str.
substring()" is used to remove the last digit of a number.
The replace() method searches a string for a value or a regular expression. The replace() method returns a new string with the value(s) replaced. The replace() method does not change the original string.
To replace text in a JavaScript string the replace() function is used. The replace() function takes two arguments, the substring to be replaced and the new string that will take its place. Regex(p) can also be used to replace text in a string.
@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');
});
});
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With