【问题标题】:How to increment the end of string using Javascript [duplicate]如何使用Javascript增加字符串的结尾[重复]
【发布时间】:2020-11-16 12:17:45
【问题描述】:

所以挑战是增加一个字符串,具体规则如下:

  • 如果字符串已经以数字结尾,数字应该是 增加 1。

  • 如果字符串不以数字结尾。数字 1 应附加到新字符串中。

例子:

foo -> foo1

foobar23 -> foobar24

foo0042 -> foo0043

foo9 -> foo10

foo099 -> foo100

我已经通过两次不同的尝试如此接近了。两者都勾选某些框,但两者都不勾选。

function incrementString (strng) {
  if (/\d/.test(strng) === true) {
    var num = +strng.match(/\d+/g)[0] + 1;    
    return strng.replace(/[1-9]/g,'') + num;
  } else {
    return strng + "1";
  }
}

这将返回字符串,将零保持在递增数字之前。但是在像“foobar099”这样的测试中,我需要返回“foobar100”但得到“foobar0100”。

function incrementString (strng) {
  if (/\d/.test(strng) === true) {
    var num = +strng.match(/\d+/g)[0] + 1;    
    return strng.replace(/\d/g,'') + num;
  } else {
    return strng + "1";
  }
}

这是另一个成功的尝试,成功地增加了诸如“foobar099”->“foobar100”之类的测试,但放弃了诸如“foobar0042”之类的测试的零,变成了“foobar43”。

谁能解决这个问题?

【问题讨论】:

  • 将数字和字符串分开并检查它们的长度,然后在数字增加后,在字符串末尾附加额外的0以及更新后的数字

标签: javascript regex parsing


【解决方案1】:

这是你想要的吗?

function incrementString(text) {
    return text.replace(/(\d*)$/, (_, t) => (+t + 1).toString().padStart(t.length, 0));
}

console.log(incrementString('foo'));
console.log(incrementString('foobar23'));
console.log(incrementString('foo0042'));
console.log(incrementString('foo9'));
console.log(incrementString('foo099'));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多