@Brilliant 是对的,+1,我只是想提供他的答案的一个版本,并进行了 2 处修改:
- 删除不必要的
negative look-ahead
运算符。
- 添加最后添加数字的功能,以防它不存在。
```
/**
* 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;
}
测试:
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');
});
});