node.js - 在 NodeJS 中为文本中的所有数字添加值

标签 node.js regex

我会替换文本中的所有数字,例如我会向所有数字添加一些值V。例如,对于 V=3:

var inp = "Try to replace thsis [11-16] or this [5] or this [1,2]";

替换应该给我:

var output = "Try to replace thsis [14-19] or this [8] or this [4,5]";

使用 RegExp 我想做一些类似的事情:

var V = 12;
var re = new RegExp(/[0-9]+/g);
var s = inp.replace(re,'$1' + V);

但显然不起作用。

最佳答案

in.replace(re,'$1' + V) 中,V 值仅添加到 $1 字符串中,字符串替换模式类似于 $112。由于您的模式不包含任何捕获组,因此替换模式将被视为文字字符串。

您可以在 replace 方法中使用回调,您可以在其中操作匹配值:

var V = 3;
var inp = "Try to replace thsis [11-16] or this [5] or this [1,2]";
var re = /[0-9]+/g;
var outp = inp.replace(re, function($0) { return parseInt($0, 10) + V; });
console.log(outp);

关于node.js - 在 NodeJS 中为文本中的所有数字添加值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48204306/

相关文章:

node.js - 尝试启动包裹开发服务器时出现问题

javascript - Imgur 通过客户端 JavaScript 上传,但不通过 Node.js。困惑的

node.js - 当我尝试将对象推送到 MongoDB 和 Nodejs 中的数组时,为什么会出现castError?

c# - 使用 Visual Studio 2013 正则表达式查找 - 如何使多个前缀无效

regex - 使用 find 和 regex 区分 .h 和 .sh

java - 使用 Java 进行源代码检测

python - python中根据非连续整数、字符和 float 分割字符串

javascript-正则表达式字母数字和特殊字符

javascript - 我的 POST 有什么问题,导致 req.body 为空

javascript - AngularJS/Jade 错误 : Argument 'MyController' is not a function, 未定义(平均值)