在javascript中,我有一个包含数字的字符串,我想将值递增一.
例:
var string = "This is a string with numbers 1 2 3 4 5 6 7 8 9 10";
var desiredResult = "This is a string with numbers 2 3 4 5 6 7 8 9 10 11";
Run Code Online (Sandbox Code Playgroud)
使用正则表达式,是否可以在匹配的反向引用上执行操作(在这种情况下是添加)?
使用Ruby 发现了类似的问题:
string.gsub(/(\d+)/) { "#{$1.to_i + 1}"}
Run Code Online (Sandbox Code Playgroud)
使用string.replace函数作为第二个参数:
var s1 = "This is a string with numbers 1 2 3 4 5 6 7 8 9 10";
var s2 = s1.replace(/\d+/g, function(x) { return Number(x)+1; });
s2; // => "This is a string with numbers 2 3 4 5 6 7 8 9 10 11"
Run Code Online (Sandbox Code Playgroud)
请注意,如果使用匹配组,则函数的第一个参数将是整个匹配,并且每个后续参数将是编号匹配组.
var x = "This is x1, x2, x3.";
var y = x.replace(/x(\d+)/g, function(m, g1) {
return "y" + (Number(g1)+1);
});
y; // => "This is y2, y3, y4."
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
827 次 |
| 最近记录: |