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()每次调用时都必须编译正则表达式。因此,字面版本的性能会更好。
相关推荐
GISer_Jing3 小时前
Three.js着色器编译机制深度解析
javascript·webgl·着色器
丷丩3 小时前
MapLibre GL JS第22课:查看本地GeoJSON
前端·javascript·map·mapbox·maplibre gl js
油炸自行车3 小时前
Claude Code 错误:API Error: 400 Failed to deserialize the JSON body into the
开发语言·javascript·json·trae·claude code·api error 400
丷丩7 小时前
MapLibre GL JS第19课:实时更新要素
前端·javascript·gis·map·mapbox·maplibre gl js
xiaohua0708day8 小时前
Lodash库
前端·javascript·vue.js
突然好热8 小时前
TS 调试技巧
前端·javascript·typescript
h64648564h8 小时前
Flutter 国际化(i18n)全指南:一键切换中/英/日多语言
前端·javascript·flutter
丷丩9 小时前
MapLibre GL JS第8课:禁用滚动缩放
javascript·mapbox·maplibre gl js
kyriewen11 小时前
面试8家前端岗位后,我发现了一个残酷的事实:AI不是加分项,是门槛
前端·javascript·面试
MageGojo14 小时前
做节日活动页时,如何用 API 快速生成对联内容
javascript·python·节日·对联生成