如何在字符串中减去一个数字?目前我有这个代码:
var existingId = "test 10 test";
let newId = existingId .replace(/\d+/g, function(match, number) {
return parseInt(number)-1;
});
这个数字并不总是在同一个位置上。我无法将数字存储在变量中。
但我的正则表达式不正确。
number
就是整个match
。该函数的参数为 (match, ...groups, index, inputString)。由于你的正则表达式中没有分组,所以你的参数number
包含了index
。 - Thomasvar s = "test 10 test"; s = s.replace(/\d+/g, function(m){ return parseInt(m, 10) - 1; });
您可以在此处查看演示:http://jsfiddle.net/6YJQx/ - Edison AugusthyparseInt
已经过时了:inputString.replace(/-?\d+/g, number => number-1)
- Thomas