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()每次调用时都必须编译正则表达式。因此,字面版本的性能会更好。
相关推荐
三8443 小时前
路由策略/控制 配置双点双向路由重发布
服务器·前端·javascript
柒和远方6 小时前
V043:BFF 层流式输出:从前端直连到生产级流式网关的架构演进
javascript·架构·node.js
用户938515635076 小时前
SSE 流式输出的工程化拐点——为什么你需要一个 BFF 层
javascript·人工智能·全栈
不简说7 小时前
JS 代码技巧 vol.4 — 10 个异步并发控制,Promise.all 这帮兄弟的踩坑实录
前端·javascript·面试
Listen·Rain10 小时前
Vue3中组件间通信详解
前端·javascript·vue.js
Listen·Rain10 小时前
Vue3中customRef详解
前端·javascript·vue.js
爱宇阳10 小时前
JavaScript 并发请求入门:Promise.all 和 Promise.allSettled 到底怎么选?
开发语言·前端·javascript
香芋芋圆10 小时前
国内常用坐标系全解析与WebGIS框架实战指南(Cesium/Mapbox/Leaflet避坑手册)
前端·javascript
sugar__salt10 小时前
Document 切割:RAG 知识库数据预处理实战
javascript·langchain·embedding·js·rag·cheerio
小粉粉hhh10 小时前
React(三)——Redux
前端·javascript·react.js