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()每次调用时都必须编译正则表达式。因此,字面版本的性能会更好。
相关推荐
openKaka_14 分钟前
为什么 React 18 之后使用 createRoot,而不是 ReactDOM.render
前端·javascript·react.js
WindrunnerMax23 分钟前
基于 Markdown-It 的无序列表折叠插件
前端·javascript·github
神三元33 分钟前
最近半年,我做了个 AI-Native 的 Agent 从零到进阶教程
前端·javascript·面试
XiYang-DING1 小时前
jQuery
前端·javascript·jquery
老王以为1 小时前
从源码到架构:React useActionState 深度剖析
前端·javascript·react.js
前端超有趣1 小时前
详解JavaScript中encodeURIComponent和decodeURIComponent的使用(附实战场景)
前端·javascript
XinZong1 小时前
业余抱团搞副业:基于OpenClaw做了一款AI社交虾聊,产品做完了,求运营思路
javascript
萧曵 丶2 小时前
Vue3组件通信全方案
前端·javascript·vue.js·typescript·vue3
Dxy12393102162 小时前
JavaScript 字符串转数值(小数)
开发语言·javascript·ecmascript
lightqjx2 小时前
【前端】前端学习三之初识JavaScript
前端·javascript·学习