字符串递增:将最后一个字符串递增 1

String increment: increment the last string by one

此代码的目的是编写一个递增字符串的函数,以创建一个新字符串。如果字符串已经以数字结尾,则该数字应递增 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([=10=], ) { return *1+1; });
//=> "foo1"
'foo999'.replace(/(\d*)$/, function([=10=], ) { return *1+1; });
//=> "foo1000"
'foo123'.replace(/(\d*)$/, function([=10=], ) { return *1+1; });
//=> "foo124"

解释:

/(\d*)$/                # match 0 or more digits at the end of string
function([=11=], ) {...}  # callback function with 2nd parameter as matched group #1
return *1+1;          # return captured number+1. *1 is a trick to convert
                        # string to number

我认为你可以大大简化你的代码:

function incrementString(input) {
    var splits = input.split(/(\d+)$/),
    num = 1;
    if (splits[1] !== undefined) num = parseInt(splits[1]) + 1;
    return splits[0] + num;
}

这会检查字符串末尾的任意数字。

function pad(number, length, filler) {
    number = number + "";
    if (number.length < length) {
        for (var i = number.length; i < length; i += 1) {
            number = filler + number;
        }
    }

    return number;
}

function incrementString (input) {
    var orig = input.match(/\d+$/);
    if (orig.length === 1) {
        orig = pad(parseInt(orig[0]) + 1, orig[0].length, '0');
        input = input.replace(/\d+$/, orig);
        return input;
    }

    return input + "1";
}

它有什么作用?

它首先检查是否有尾随数字。如果是,请递增它并用零填充它(使用 "pad" 函数,您可以自己对其进行排序)。

string.replace 是一个函数,它使用参数 1 要搜索的子字符串(字符串,正则表达式),参数 2 要替换为(字符串,函数)的元素。

在这种情况下,我使用正则表达式作为第一个参数和递增的填充数字。

正则表达式非常简单:\d 表示 "integer",+ 表示 "one or more of the preceeding",表示一位或多位数字。 $表示字符串结束。

有关正则表达式的更多信息(在 JavaScript 中):https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/RegExp(感谢@Casimir et Hippolyte link)

function incrementString (strng) {
      //separateing number from string
        let x = (strng).replace( /^\D+/g, '');
      //getting the length of original number from the string
      let len = x.length;

      //getting the string part from strng
      str = strng.split(x);

      //incrementing number by 1
      let number = Number(x) + 1 + '';

      //padding the number with 0 to make it's length exactly to orignal number
      while(number.length < len){
        number = '0' + number;
      }

    //new string by joining string and the incremented number
      str = (str + number).split(',').join('');
      //return new string
      return str;
    }

我的快速回答是:

let newStr = string.split('');
let word = [];
let num = [];
for (let i = 0 ; i<string.length ;i++){
  isNaN(string[i])? word.push(string[i]) : num.push(string[i]) 
}
let l=num.length-1;
let pureNum=0;
for (let i = 0 ; i<num.length ;i++){
  pureNum += num[i] * Math.pow(10,l);
  l--;
}
let wordNum = (pureNum+1).toString().split('');
for (let i = wordNum.length ; i<num.length ;i++){
  wordNum.unshift("0");
}
return word.join("")+wordNum.join(""); 
}

我见过的同时考虑前导零、非数字结尾和空字符串的最简洁的方法是:

''.replace(/[0-8]?9*$/, w => ++w)
//=> 1

'foo'.replace(/[0-8]?9*$/, w => ++w)
//=> foo1

'foo099'.replace(/[0-8]?9*$/, w => ++w)
//=> foo100

'foo999'.replace(/[0-8]?9*$/, w => ++w)
//=> foo1000