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()每次调用时都必须编译正则表达式。因此,字面版本的性能会更好。
相关推荐
Never_Satisfied4 小时前
在JavaScript / HTML中,数组查找第一个符合要求元素
开发语言·javascript·html
HelloReader5 小时前
Tauri 2 创建项目全流程create-tauri-app 一键脚手架 + Tauri CLI 手动接入
前端·javascript·vue.js
shix .6 小时前
旅行网站控制台检测
开发语言·前端·javascript
henry1010107 小时前
DeepSeek生成的网页小游戏 - 迷你高尔夫
前端·javascript·游戏·html
薛一半7 小时前
React的组件
前端·javascript·react.js
薛一半8 小时前
React三大属性之props
前端·javascript·react.js
用户5757303346248 小时前
🔥 前端必考!AJAX 数据请求全解析,async true/false 区别一次搞懂
javascript
烤麻辣烫9 小时前
正则表达式快速掌握
前端·javascript·学习·正则表达式·html
心之语歌10 小时前
flutter 父子组件互相调用方法,值更新
前端·javascript·flutter
肖。354878709410 小时前
html中onclick误区,后续变量会更改怎么办?
android·java·javascript·css·html