字符串中的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会更新我的答案。