如何用自身+1替换字符串中的数字?

How to replace a number within a string by itself + 1?

我有一个像 "We have a foobar which can provide a maximum of 20 foo per bar." 这样的字符串我想替换每个出现的 "a maximum of " + a <number++ 任意长度的数字。上述字符串将导致:

"We have a foobar which can provide <21 foo per bar."

我想到了类似的东西:

string.replace("/maximum\sof\s\d+/ig", `<${++}`)

但我无法让它工作,因为 $1 仅反向引用整个捕获组,而不是单个数字。我也在为字符串格式而苦恼。

您可以使用回调函数和捕获组

maximum\sof\s(\d+)
  • maximum\sof\s - 匹配 maximum of
  • (\d+) - 匹配一个或多个数字(捕获组 1)

在回调中,我们可以使用捕获的组来替换我们想要的任何额外内容

let str = "We have a foobar which can provide a maximum of 20 foo per bar."
let replaced = str.replace(/maximum\sof\s(\d+)/ig, (_, g1) => '<' + (+g1+1))

console.log(replaced)

替换可以使用函数:

let input = "We have a foobar which can provide a maximum of 20 foo per bar.";

console.log(
  input.replace(/(?:\ba )?maximum of ([0-9]+)\b/, function (all, max) {
    return "<" + (max / 1 + 1);
  })
);

这匹配 /(?:\ba )?maximum of ([0-9]+)\b/(带有可选的前导分词符和 ),然后对结果运行一个函数:整个匹配(我们不使用)然后是数字.然后我们可以将该段与修改后的数字拼接在一起。我除以 1 以确保 max 被视为一个数字(否则它将是一个字符串,因此连接到 201 而不是 21)。