【发布时间】:2020-07-12 17:19:09
【问题描述】:
我正在尝试在 RegEx 中使用变量,但遇到了问题。这是我的功能:
const truncateNum = (num, place = 2) => {
const matcher = `/^-?\d+(?:\.\d{0,${place}})?/`;
const re = new RegExp(matcher);
return num.toString().match(re)[0];
};
运行时出现以下错误:
Uncaught TypeError: Cannot read property '0' of null
我在这里做错了什么?
【问题讨论】:
-
问题在于元字符转义。将此
^\\-?\\d+(?:\\.\\d{0,${place}})?放在您的模板文字中以解决问题。
标签: javascript regex