javascript - 字符串增量 : increment the last string by one

标签 javascript regex string numbers increment

这段代码的目的是编写一个递增字符串的函数,以创建一个新字符串。如果字符串已以数字结尾,则该数字应增加 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/

相关文章:

javascript - 如何将数据附加到 mongodb 中的对象属性

正则表达式 - 在末尾将多个单词和空格与十进制数字分开

php - 在 RLIKE 正则表达式中使用 PHP 变量

c - 从行中读取单词

Python - 为什么不总是缓存所有不可变对象(immutable对象)?

PHP 检查升序/降序数字

javascript - 数组/对象排序

Javascript 检测内部 html 何时更改

javascript - 如何在 javascript 中解析 Dailymotion 视频网址

javascript - ActionScript 3 中类似 JSObject 的东西?