这段代码的目的是编写一个递增字符串的函数,以创建一个新字符串。如果字符串已以数字结尾,则该数字应增加 1。如果字符串不以数字结尾,则应将数字 1 附加到新字符串。例如“foo123”-->“foo124”或“foo”-->“foo1”。 使用下面的代码,几乎所有测试用例都通过了,除了“foo999”的极端情况没有打印出“foo1000”。我知道应该有一种方法可以使用正则表达式来解决我的问题,但我对此不太熟悉。有人可以帮忙吗?
function incrementString (input) {
var reg = /[0-9]/;
var result = "";
if(reg.test(input[input.length - 1]) === true){
input = input.split("");
for(var i = 0; i < input.length; i++){
if(parseInt(input[i]) === NaN){
result += input[i];
}
else if(i === input.length - 1){
result += (parseInt(input[i]) + 1).toString();
}
else{
result += input[i];
}
}
return result;
}
else if (reg.test(input[input.length - 1]) === false){
return input += 1;
}
}
最佳答案
您可以使用带有回调的替换:
'foo'.replace(/(\d*)$/, function($0, $1) { return $1*1+1; });
//=> "foo1"
'foo999'.replace(/(\d*)$/, function($0, $1) { return $1*1+1; });
//=> "foo1000"
'foo123'.replace(/(\d*)$/, function($0, $1) { return $1*1+1; });
//=> "foo124"
说明:
/(\d*)$/ # match 0 or more digits at the end of string
function($0, $1) {...} # callback function with 2nd parameter as matched group #1
return $1*1+1; # return captured number+1. $1*1 is a trick to convert
# string to number
关于javascript - 字符串增量 : increment the last string by one,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29601303/