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()每次调用时都必须编译正则表达式。因此,字面版本的性能会更好。
相关推荐
GISer_Jing1 小时前
Three.JS渲染架构解读
java·javascript·架构
时寒的笔记2 小时前
day13~14核心案例某采招网
开发语言·javascript·ecmascript
智商不够_熬夜来凑2 小时前
【Picker】单选多选
前端·javascript·vue.js
米饭不加菜3 小时前
Typora 原生流程图语法完全指南(Flowchart.js)
前端·javascript·流程图
scan7243 小时前
langgraphy条件边
前端·javascript·html
用户938515635074 小时前
《JS 对象知识地图:10 个小节,从字面量到原型链全覆盖》
javascript
YAwu114 小时前
JavaScript this 底层机制剖析
前端·javascript
tedcloud1234 小时前
wifi-densepose部署教程:构建无线人体感知系统
服务器·javascript·网络·typescript·ocr
用户852495071844 小时前
帮你搞清楚对付js里对象的小妙招^_^
javascript