【问题标题】:How do you use a template literal in a match RegEx? [duplicate]如何在匹配 RegEx 中使用模板文字? [复制]
【发布时间】: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


【解决方案1】:

您的代码存在一些问题。

第一个是当你将正则表达式定义为字符串时,它不需要//标记,而且反斜杠也需要双转义\\d+

第二个是如果正则表达式不匹配,num.toString().match(re) 将返回null,因此您在尝试对null[0] 进行数组查找时会遇到异常。

let truncateNum = (num, place = 2) => {
  const  matcher = `^-?\\d+(?:\\.\\d{0,${place}})?`; console.log(matcher);
  const  re      = new RegExp(matcher);
  const  match   = num.toString().match(re);
  const  result  = match && match[0] || '0'
  return result;
};

【讨论】:

  • 我明白了。感谢您的解决方案!
猜你喜欢
  • 1970-01-01
  • 2010-09-25
  • 2013-01-29
  • 1970-01-01
  • 2011-06-16
  • 2021-11-24
  • 2021-01-23
  • 1970-01-01
相关资源
最近更新 更多