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()每次调用时都必须编译正则表达式。因此,字面版本的性能会更好。
相关推荐
Jenlybein7 小时前
快速了解熟悉 Vite ,即刻上手使用
前端·javascript·vite
Ailrid7 小时前
@virid/core:用游戏引擎的思维来写应用-高度确定性的应用开发引擎
javascript
SuperEugene9 小时前
Vue3 组件复用设计:Props / 插槽 / 组合式函数,三种复用方式选型|组件化设计基础篇
前端·javascript·vue.js
nFBD29OFC9 小时前
利用Vue元素指令自动合并tailwind类名
前端·javascript·vue.js
zk_one11 小时前
【无标题】
开发语言·前端·javascript
AIBox36512 小时前
openclaw api 配置排查与接入指南:网关启动、配置文件和模型接入全流程
javascript·人工智能·gpt
precious。。。12 小时前
1.2.1 三角不等式演示
前端·javascript·html
阿珊和她的猫12 小时前
TypeScript 中的 `extends` 条件类型:定义与应用
javascript·typescript·状态模式
众创岛13 小时前
iframe的属性获取
开发语言·javascript·ecmascript
echome88814 小时前
JavaScript Promise 与 async/await 实战:5 个高频异步编程场景的优雅解决方案
开发语言·javascript·ecmascript