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()每次调用时都必须编译正则表达式。因此,字面版本的性能会更好。
相关推荐
还不秃顶的计科生1 小时前
defaultdict讲解
开发语言·javascript·ecmascript
花归去1 小时前
echarts 柱状图包含右侧进度
开发语言·前端·javascript
沐浴露z1 小时前
学习通“只能录入不能粘贴” 解决方案与原理分析
javascript
Sapphire~1 小时前
Vue3-03 熟悉src文件夹及Vue文件格式
前端·javascript·vue.js
ChangYan.2 小时前
Electron使用ffi-napi报错External buffers are not allowed解决办法
前端·javascript·electron
阿民_armin2 小时前
移动端长列表「返回原位置」的完整实践
前端·javascript·vue.js
Arnbit1on2 小时前
使用docxtemplater进行Word文档的自动填充
javascript
张元清2 小时前
告别 Promise.all 的依赖困境:better-all 如何优雅管理异步任务
前端·javascript·面试
开源之眼2 小时前
github star 加星多的从 React 到 Web3D:前端开发者的三维世界入门指南
javascript·面试
pas1363 小时前
30-mini-vue 更新 element 的 props
前端·javascript·vue.js