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()每次调用时都必须编译正则表达式。因此,字面版本的性能会更好。
相关推荐
wuxia21186 小时前
在5种环境中编写点击元素改变内容和颜色的JavaScript程序
javascript·微信小程序·vue·jquery·react
铁皮饭盒7 小时前
Bun + SQLite 10个实用技巧
前端·javascript·后端
想吃火锅10058 小时前
【leetcode】20.有效的括号js
linux·javascript·leetcode
aaaa954726658 小时前
终端与IDE形态Vibe Coding实测:主流AI编程工具迁移与迭代对比
javascript·react.js·ecmascript
晓得迷路了8 小时前
栗子前端技术周刊第 133 期 - Angular v22、React 编译器 Rust 版、pnpm 11.5...
前端·javascript·css
云浪8 小时前
别再让用户干等了:用 Express + SSE 实现《红楼梦》AI 问答实时输出
javascript·后端·node.js
晓13138 小时前
【Cocos Creator 3.x】篇——第五章 项目实战优化技术
前端·javascript·游戏引擎
AZaLEan__8 小时前
JavaScript 基础语法
开发语言·javascript·ecmascript
有梦想的程序星空8 小时前
【环境配置】使用 Vue CLI 构建 Vue 项目脚手架完整指南
前端·javascript·vue.js
影视飓风TIM8 小时前
C++ 核心语法笔记:拷贝构造、深浅拷贝与运算符重载
java·开发语言·javascript