关于 javascript:如何将字符串中的数字本身替换为 1?

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

我有一个字符串,例如"我们有一个 foobar,每个 bar 最多可以提供 20 个 foo"。我想用 <number++ 替换每次出现的"最多"任意长度的数字。上述字符串将导致:

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

我想过类似的事情:

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

但我不能让它作为 $1 只反向引用整个捕获组而不是单个数字。我也在字符串格式方面挣扎。


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

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

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

1
2
3
4
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)


替换可以使用一个函数:

1
2
3
4
5
6
7
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/(带有可选的前导断字和 a),然后对结果运行一个函数:整个匹配(我们不使用),然后是数字。然后我们可以将该段与修改后的数字拼接在一起。我除以 1 以确保 max 被视为一个数字(否则它会是一个字符串,因此连接到 201 而不是 21)。