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()每次调用时都必须编译正则表达式。因此,字面版本的性能会更好。
相关推荐
yhole1 小时前
SQL中的REGEXP正则表达式使用指南
数据库·sql·正则表达式
Kel1 小时前
深入剖析 openai-node 源码:一个工业级 TypeScript SDK 的架构之美
javascript·人工智能·架构
SuperEugene2 小时前
Vue3 模板语法规范实战:v-if/v-for 不混用 + 表达式精简,避坑指南|Vue 组件与模板规范篇
开发语言·前端·javascript·vue.js·前端框架
Luna-player2 小时前
Vue 3 + Vue Router 的路由配置,简单示例
前端·javascript·vue.js
敲代码的约德尔人2 小时前
JavaScript 设计模式完全指南
javascript·设计模式
angerdream3 小时前
最新版vue3+TypeScript开发入门到实战教程之Vue3详解props
javascript·vue.js
~欲买桂花同载酒~3 小时前
项目优化-vite打包优化
前端·javascript·vue.js
kyriewen4 小时前
JavaScript 继承的七种姿势:从“原型链”到“class”的进化史
前端·javascript·ecmascript 6
wangfpp4 小时前
性能优化,请先停手:为什么我劝你别上来就搞优化?
前端·javascript·面试