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()每次调用时都必须编译正则表达式。因此,字面版本的性能会更好。
相关推荐
吴声子夜歌13 小时前
正则表达式——简单的模式匹配
正则表达式
大家的林语冰14 小时前
🎉 Vercel 官宣 Next 16.3 正式发布,GitHub 第一全栈框架再次进化!
前端·javascript·前端框架
张元清15 小时前
React useEvent Hook:告别过期闭包的稳定回调 (2026)
javascript·react.js
用户9385156350715 小时前
从 DOM 编程到声明式 UI:React useRef 与 useState 底层全解析
前端·javascript·react.js
小月土星16 小时前
19.LeetCode 删除链表的倒数第 N 个节点 超详细题解(JS 版)
javascript
就叫飞六吧16 小时前
codex无直接proxy 配置,拓展proxy方案
javascript·ai编程
kisshyshy16 小时前
前端路由进化史:从刷新白屏到SPA,手写一个Hash路由就懂了!
前端·javascript·react.js
Sterting16 小时前
第 8 节:表单 — 前端校验的第一道防线
前端·javascript
java1234_小锋17 小时前
Vue3专题 - 条件渲染
前端·javascript·vue.js
嘟嘟071717 小时前
从零理解 useRef:React 中操作 DOM 与持久化变量的唯一桥梁
javascript