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()每次调用时都必须编译正则表达式。因此,字面版本的性能会更好。
相关推荐
竹林81814 小时前
RainbowKit快速集成多链钱包连接,我如何从“连不上”到“丝滑切换”
前端·javascript
No8g攻城狮14 小时前
【前端】Vue 中 const、var、let 的区别
前端·javascript·vue.js
fishmemory7sec14 小时前
Vue大屏自适应容器组件:v-scale-screen
前端·javascript·vue.js
饺子不吃醋14 小时前
Promise原理、手写与 async、await
前端·javascript
糯米团子74916 小时前
react速通-3
javascript·react.js·前端框架
心连欣16 小时前
从静态页面到动态交互:DOM操作的核心API解析
前端·javascript·api
零瓶水Herwt16 小时前
Javascript常用设计模式
javascript
风骏时光牛马16 小时前
C Shell脚本编程与系统管理技术实践指南
javascript
烛衔溟16 小时前
TypeScript this 参数类型与全局 this
javascript·ubuntu·typescript
qq_120840937116 小时前
Three.js 工程向:GLTFLoader 管线、Draco/KTX2 与资源管理
开发语言·javascript·ecmascript