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()每次调用时都必须编译正则表达式。因此,字面版本的性能会更好。
相关推荐
张元清2 小时前
React useUpdateEffect Hook:跳过首次渲染(2026)
javascript·react.js
名字还没想好☜3 小时前
React createPortal 实战:模态框逃出 overflow:hidden、事件冒泡与焦点管理
前端·javascript·react.js·ecmascript·react·createportal
fthux10 小时前
RenoPit 能为普通业主做什么?看懂图纸、审查合同,提前发现装修坑
javascript·人工智能·ai·开源·github·chrome扩展·open source·edge扩展·firefox扩展
仿生狮子11 小时前
✂️ Nuxt 最简单的字体裁剪工具:Fontize
javascript·vue.js·nuxt.js
魔力女仆14 小时前
分享一个 JS 鼠标跟随贪吃蛇背景库
开发语言·javascript·计算机外设
别惊醒渔人16 小时前
Vue3 Diff 优化:最长递增子序列 LIS
前端·javascript·vue.js
Larcher16 小时前
从“加载模型”界面到端侧推理:拆解一个 React + WebGPU 大模型 Demo
javascript·后端
Larcher17 小时前
从状态快照到惰性初始化:读懂 React useState 的三个关键场景
javascript·人工智能·后端
Hilaku18 小时前
工作 5 年后,决定你薪资上限的究竟是什么?
前端·javascript·程序员
weixin_BYSJ198719 小时前
springboot校园自习室管理小程序---附源码32142
java·javascript·spring boot·python·django·flask·php