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()每次调用时都必须编译正则表达式。因此,字面版本的性能会更好。
相关推荐
巴博尔42 分钟前
UNIAPP中NVUE页面 动画
android·前端·javascript·ios·uni-app
猫头虎-前端技术1 小时前
JS 作用域与闭包:从变量提升到闭包陷阱的超详细解析
开发语言·javascript·云计算·bootstrap·ecmascript·openstack·perl
她说人狗殊途3 小时前
基于 vue-cli 创建
前端·javascript·vue.js
大家的林语冰4 小时前
Deno 2.8 正式发布,再次超越 Bun,史上最大的次版本升级诞生!
前端·javascript·node.js
影寂ldy4 小时前
C#数组的属性和方法(Clear / Copy / IndexOf )
开发语言·javascript·c#
Brave & Real4 小时前
小程序 const 在js中以及与同类的var和let之间的差异
javascript·微信小程序·小程序
米丘5 小时前
React 19.x 的 lazy 与 Suspense
前端·javascript·react.js
ZC跨境爬虫6 小时前
跟着 MDN 学CSS day_21:(图像溢出控制与表单元素样式定制)
前端·javascript·css·ui·交互
riuphan6 小时前
JavaScript 中的 this 关键字
javascript
掰头战士6 小时前
五分钟带你深入了解 this
javascript