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()每次调用时都必须编译正则表达式。因此,字面版本的性能会更好。
相关推荐
Hello.Reader4 小时前
Elasticsearch JS 客户端子客户端(Child Client)实践指南
大数据·javascript·elasticsearch
android大哥4 小时前
WeChatExtension-ForMac 微信小插件
javascript
辰九九6 小时前
Uncaught URIError: URI malformed 报错如何解决?
前端·javascript·浏览器
小高0076 小时前
React useMemo 深度指南:原理、误区、实战与 2025 最佳实践
前端·javascript·react.js
LuckySusu6 小时前
【js篇】深入理解类数组对象及其转换为数组的多种方法
前端·javascript
LuckySusu6 小时前
【js篇】数组遍历的方法大全:前端开发中的高效迭代
前端·javascript
LuckySusu6 小时前
【js篇】for...in与 for...of 的区别:前端开发中的迭代器选择
前端·javascript
小高0077 小时前
协商缓存和强缓存
前端·javascript·面试
前端Hardy7 小时前
HTML&CSS&JS:超酷炫的一键登录页面
前端·javascript·css
该用户已不存在8 小时前
2025年,Javascript后端应该用 Bun、Node.js 还是 Deno?
javascript·后端