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()每次调用时都必须编译正则表达式。因此,字面版本的性能会更好。
相关推荐
xiaofeichaichai13 小时前
ES 新特性九年速览:从 ES2016 到 ES2024
前端·javascript·es6
放下华子我只抽RuiKe513 小时前
FastAPI 全栈后端(四):认证与授权
开发语言·前端·javascript·python·深度学习·react.js·fastapi
如果超人不会飞14 小时前
WebMCP:当浏览器学会和 AI「说人话」,你的网页就成了智能体的游乐场
javascript
整点可乐14 小时前
cesium实现全景图加载
javascript·cesium
dualven_in_csdn15 小时前
一键起飞调用示例
android·java·javascript
meilindehuzi_a15 小时前
通俗易懂掌握树与二叉树:定义、核心概念与JS实现遍历
javascript·ecmascript
胡志辉15 小时前
深入浅出理解浏览器事件循环:从一道输出题讲到 Chrome 源码
前端·javascript·面试
gz-郭小敏16 小时前
优化横向滚动展示大量数据的时候数据晃动问题
前端·javascript·html·css3
IMPYLH18 小时前
HTML 的 <a>元素
前端·javascript·html