【问题标题】:RegExp Object Literal notation vs Constructor notation difference [duplicate]RegExp Object Literal notation vs Constructor notation差异[重复]
【发布时间】:2016-06-02 04:09:20
【问题描述】:
var digits = "B2";
var re = new RegExp("/\d+/");
console.log(/\d+/.test(digits));
console.log("digits matches to :", digits.match(re));

为什么 digits.match(re) 返回 NULL 而 .test 返回 true? 当我只运行 digits.match("/\d+/");我得到了正确的答案。

【问题讨论】:

  • 我也收到了nulldigits.match("/\d+/")。你确定那是你使用的代码吗?

标签: javascript regex


【解决方案1】:

new RegExp() 语法不使用正斜杠 / 作为分隔符。假设整个字符串是正则表达式。此外,必须对反斜杠进行转义,因为当您不引用转义字符时,这是字符串的要求。

这些都是一样的:

digits.match(new RegExp("\\d+")); // 2

digits.match(/\d+/); // 2

【讨论】:

  • 我想强调一下,反斜杠转义非常重要,因为错误可能会在意想不到的时候潜入,例如 this hard-to-spot time\b
猜你喜欢
  • 1970-01-01
  • 2018-02-28
  • 2016-06-18
  • 1970-01-01
  • 2014-02-01
  • 1970-01-01
  • 2013-11-13
相关资源
最近更新 更多