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()每次调用时都必须编译正则表达式。因此,字面版本的性能会更好。
相关推荐
coderyi18 分钟前
LLM Agent 浅析
前端·javascript·人工智能
我叫黑大帅20 分钟前
TypeScript 6.0 弃用选项错误 TS5101 解决方法
javascript·后端·面试
科雷软件测试23 分钟前
使用python+Midscene.js AI驱动打造企业级WEB自动化解决方案
前端·javascript·python
We་ct1 小时前
LeetCode 120. 三角形最小路径和:动态规划详解
前端·javascript·算法·leetcode·typescript·动态规划
changshuaihua0013 小时前
React 入门
前端·javascript·react.js
掘金安东尼4 小时前
本周前端与 AI 技术情报|前端下一步 #462
前端·javascript·面试
qq_12084093714 小时前
Three.js 工程向:实例化渲染 InstancedMesh 的批量优化
前端·javascript
WebInfra4 小时前
Rspack 2.0 正式发布!
前端·javascript·前端框架
Highcharts.js5 小时前
在 React 中使用 useState 和 @highcharts/react 构建动态图表
开发语言·前端·javascript·react.js·信息可视化·前端框架·highcharts
|晴 天|6 小时前
Vue 3 实战:打造可拖拽歌词、播放列表的嵌入式音乐播放器
前端·javascript·vue.js