JS正则表达式构造函数和正则表达式字面量的区别

背景

笔者在使用正则表达式的过程中,经常看到两种使用方式,比较好奇这两种方式有什么不同。

一种是 正则表达式构造函数 :new RegExp("[xxx]")

另一种是 正则表达式字面量: /[xxx]/

于是,就去网上搜了一下...结果看到国外有老哥也在问这个问题:

区别

  • 回答原文:
  • literal REGEX can't accept dynamic input, whereas the constructor can, because the pattern is specified as a string.
  • literal syntax is compliled only once, while the new Regexp() form must compile the regular expression each time it is called. - so performance will be better with the literal version.

翻译一下,关键区别在于:

  • 正则表达式字面量不能接受动态输入,即来自变量,而构造函数可以,因为模式被指定为字符串。
  • 正则表达式字面量语法只编译一次,而构造函数 Regexp()每次调用时都必须编译正则表达式。因此,字面版本的性能会更好。
相关推荐
salt3 小时前
HALCON字符串处理实战:从基础操作到正则表达式应用
正则表达式·halcon·工业视觉·字符串处理
半新半旧3 小时前
正则表达式
正则表达式
程序员Sonder3 小时前
黑马java----正则表达式(一文弄懂)
java·正则表达式·新人首发
doris82043 小时前
Python 正则表达式 re.findall()
java·python·正则表达式
python_chai3 小时前
正则表达式从入门到实战:Python高效处理文本的终极秘籍
正则表达式·re模块·文本处理·pothon·贪婪匹配
Mrliu__3 小时前
Python高级技巧(六):正则表达式
开发语言·python·正则表达式
YC运维3 小时前
Shell 正则表达式完全指南
正则表达式
AhoJustLikeU3 小时前
萌新学习正则表达式日志
正则表达式
Highcharts.js3 小时前
数据之美:用Highcharts打造专业级弧线图
javascript·数据库·highcharts·图表开发·弧线图
SuperEugene4 小时前
错误处理与 try/catch:真实项目里应该捕什么错?
前端·javascript·面试