JavaScript中对字符串中的数字进行减一操作

3
如何在字符串中减去一个数字?目前我有这个代码:
var existingId = "test 10 test";

let newId = existingId .replace(/\d+/g, function(match, number) {
       return parseInt(number)-1;
});

这个数字并不总是在同一个位置上。我无法将数字存储在变量中。

但我的正则表达式不正确。


.split(' ') 和 .join('') 将会帮助你。 - Dellirium
1
是的,但你的参数不正确。你的 number 就是整个 match。该函数的参数为 (match, ...groups, index, inputString)。由于你的正则表达式中没有分组,所以你的参数 number 包含了 index - Thomas
1
最好的方法取决于许多因素。数字是否总是在字符串的相同位置?字符串是否可以有多个数字?如果需要,您无法将数字存储在变量中并通过连接生成字符串吗? - Jonah
尝试运行以下代码:var s = "test 10 test"; s = s.replace(/\d+/g, function(m){ return parseInt(m, 10) - 1; });您可以在此处查看演示:http://jsfiddle.net/6YJQx/ - Edison Augusthy
@Edison 即使 parseInt 已经过时了:inputString.replace(/-?\d+/g, number => number-1) - Thomas
显示剩余3条评论
2个回答

4
你差不多懂了。
var existingId = "test 10 test";

let newId = existingId.replace(/\d+/g, function(match) {
    return parseInt(match) - 1;
});

0

使用match参数代替数字

let newId = existingId.replace(/\d+/g, function (match, number) {
                return parseInt(match) - 1;
);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接