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()每次调用时都必须编译正则表达式。因此,字面版本的性能会更好。
相关推荐
久爱@勿忘12 小时前
uniapp H5 图片压缩并且转blob
前端·javascript·uni-app
Dashingl12 小时前
uni-app 页面传值 报错:TypeError: $t.setAttribute is not a function
前端·javascript·uni-app
甄心爱学习12 小时前
【项目实训】法律文书智能摘要系统2
前端·javascript·vue.js
早點睡39013 小时前
ReactNative项目OpenHarmony三方库集成实战:react-native-fs
javascript·react native·react.js
lxh011313 小时前
蜗牛排序题解
javascript·算法
一只小阿乐13 小时前
react 中的Zustand的store使用
前端·javascript·react.js·zustand
我命由我1234513 小时前
Vue3 开发中,字符串中的 <br\> 标签被直接当作文本显示出来了,而不是被解析为 HTML 换行标签
开发语言·前端·javascript·vue.js·html·ecmascript·html5
早點睡39013 小时前
ReactNative项目OpenHarmony三方库集成实战:react-native-inappbrowser(也可以考虑WebView)
javascript·react native·react.js
北风toto13 小时前
Vue多文件学习项目综合案例——面经基础版,黑马vue教程
javascript·vue.js·学习
浪扼飞舟14 小时前
WPF输入验证(ValidationRule)
java·javascript·wpf