const detailFontSize = fontSize ? fontSize.replace(/(\d+)/, $1-2) : '';
比如fontSize是“12pt”,我希望修改为“10pt”。如何用$1进行replace函数中的数字运算?
上面的代码不起作用,因为 $1 未定义。如果我添加引号,它将变成“12-2pt”
最佳答案
您可以使用函数作为 .replace() 的第二个参数来操作匹配的值:
const fontSize = '12pt';
const detailFontSize = fontSize ? fontSize.replace(/(\d+)/, m => Number(m) - 2) : '';
console.log(detailFontSize)
关于javascript - 如何在js替换函数中进行数字运算?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64869268/