Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/shell/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
字符串中的Javascript减量数字_Javascript - Fatal编程技术网

字符串中的Javascript减量数字

字符串中的Javascript减量数字,javascript,Javascript,如何减少字符串中的数字?现在我有了这个: var existingId = "test 10 test"; let newId = existingId .replace(/\d+/g, function(match, number) { return parseInt(number)-1; }); 号码并不总是在同一个地方。我无法将数字存储在变量中 但我的正则表达式不正确 你差点就成功了 var existingId = "test 10 test"; let newId

如何减少字符串中的数字?现在我有了这个:

var existingId = "test 10 test";

let newId = existingId .replace(/\d+/g, function(match, number) {
       return parseInt(number)-1;
});
号码并不总是在同一个地方。我无法将数字存储在变量中

但我的正则表达式不正确

你差点就成功了

var existingId = "test 10 test";

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

使用匹配参数代替数字

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

.split(“”)和.join(“”)会帮助你是的,但你的论点不是。您的
号码
是您的全部
匹配项
。函数的参数是(匹配、…组、索引、inputString)。因为您的正则表达式中没有组,所以您的参数
number
包含
索引
从我的角度来看,它看起来是可以接受的。最好的方法取决于很多事情。数字是否总是在字符串中的同一位置?字符串可以有多个数字吗?有什么原因不能将数字存储在变量中,并在需要时通过连接生成字符串?@Jonah good questions会更新我的答案。