题目
Examples:
foo -> foo1
foobar23 -> foobar24
foo0042 -> foo0043
foo9 -> foo10
foo099 -> foo100
我的解法
function incrementString (strng) {
let matchNum = /[0-9]*$/
let num = strng.match(matchNum)
if (num) {
let numb = num[0]
let alp = strng.slice(0, num.index)
let num2 = +numb
num2++;
if (num2.toString().length >= numb.length) {
return alp + num2.toString()
} else {
let lack = numb.length - num2.toString().length
for(let i = 0; i< lack; i++ ) {
alp += '0'
}
return alp + num2.toString()
}
} else {
return strng + '1'
}
}
最佳解法
function incrementString(input) {
if(isNaN(parseInt(input[input.length - 1]))) return input + '1';
return input.replace(/(0*)([0-9]+$)/, function(match, p1, p2) {
var up = parseInt(p2) + 1;
return up.toString().length > p2.length ? p1.slice(0, -1) + up : p1 + up;
});
}