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()每次调用时都必须编译正则表达式。因此,字面版本的性能会更好。
相关推荐
এ慕ོ冬℘゜3 小时前
jQuery 核心方法
前端·javascript·jquery
阳火锅3 小时前
老板要周报?我说不用,代码提交就是进度
前端·javascript·vue.js
chjif3 小时前
一张照片和一段声音如何生成口播视频:MiniMax H3 音画同步实测
java·前端·javascript
FungLeo3 小时前
成为全栈·Node 后端篇·后端工程从零搭建:TypeScript、目录与热更新
javascript·typescript·node 后端
Y3815326625 小时前
body-upload-js
前端·javascript·浏览器·深拷贝·数据克隆
Json____5 小时前
java-宿舍安全卫生检查系统项目源码
java·前端·javascript·课程设计·it学习·wwwoop.com
AbelTomato5 小时前
博客评论系统搭建回顾
javascript·typescript·cloudflare·supabase·hyperdrive
梦醒沉醉5 小时前
4、函数function
javascript
摇滚侠6 小时前
《SpringBoot 3:入门与应用实战》第 9 章 使用 WebMvc 开发应用 阅读笔记 22
javascript·spring boot·笔记
xiaominlaopodaren6 小时前
three.js地图视口瓦片(一):屏幕角点射线
javascript·gis·three.js