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()每次调用时都必须编译正则表达式。因此,字面版本的性能会更好。
相关推荐
渔舟小调14 分钟前
P19 | 前端加密通信层 pikachuNetwork.js 完整实现
开发语言·前端·javascript
qq_120840937133 分钟前
Three.js 工程向:Draw Call 预算治理与渲染批处理实践
前端·javascript
不会聊天真君6473 小时前
JavaScript基础语法(Web前端开发笔记第三期)
前端·javascript·笔记
齐鲁大虾3 小时前
新人编程语言选择指南
javascript·c++·python·c#
码路飞4 小时前
玩了一圈 AI 编程工具,Background Agent 才是让我真正震撼的东西
前端·javascript
林恒smileZAZ4 小时前
Three.js实现更真实的3D地球[特殊字符]动态昼夜交替
开发语言·javascript·3d
月月大王的3D日记4 小时前
别再复制粘贴了,从零拆解 3D 场景的诞生过程
javascript
昭昭日月明5 小时前
前端仔速通 Python
javascript·python
SailingCoder5 小时前
Electron 安全IPC核心:contextBridge 安全机制
javascript·安全·electron