javascript - Javascript "initialize"什么时候是 RegEx 模式?

标签 javascript regex

出于性能原因,我注意声明一次 RegEx 模式并在可能的情况下重复使用。我不完全确定为什么 - 我可能在很多年前读过一次并且已经被归档在 ol' 头骨海绵中。

我发现自己处于大量使用 regex 的情况下,于是我想到了……是声明一个 RegEx 模式“实例化”或“初始化”该模式,还是只是存储该模式直到需要它?

var NonNumbers = /[^0-9]/g; //"initialized" here?
"h5u4i15h1iu".replace(NonNumbers, "*"); //or "initialized" here?

也许 RegExp() 实际上创建了一个并且文字等待直到它被使用,即使这两个模式返回相同的结果?

var NonNumbers = /[^0-9]/g; //just stores the pattern
var NonNumbers = RegExp(/[^0-9]/, 'g'); //actually creates the RegExp

只是有点痒,希望懂内情的人能挠一下。

最佳答案

来自Mozilla spec :

You construct a regular expression in one of two ways:

Using a regular expression literal, which consists of a pattern enclosed between slashes, as follows:

var re = /ab+c/;

Regular expression literals provide compilation of the regular expression when the script is loaded. If the regular expression remains constant, using this can improve performance.

Or calling the constructor function of the RegExp object, as follows:

var re = new RegExp('ab+c');

Using the constructor function provides runtime compilation of the regular expression. Use the constructor function when you know the regular expression pattern will be changing, or you don't know the pattern and are getting it from another source, such as user input.

由于规范表明正则表达式在使用文字语法时正在编译,因此也可以安全地假设它在此时被初始化为一个完整的、真正的正则表达式对象。

使用字面量的另一个好处是正则表达式可以被驻留,这意味着如果在多个地方发现相同的正则表达式字面量,两个字面量可以引用同一个对象,从而节省内存和初始化成本。

关于javascript - Javascript "initialize"什么时候是 RegEx 模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44787314/

相关文章:

Javascript - div 在滚动问题上覆盖 div

javascript - JavaScript 如何使新页面包含更多 JavaScript?

javascript - 如何使用 JavaScript 替换字符串中除第一个和最后一个字符之外的所有字符

javascript - 合并字符串

javascript - 如何编辑首选联系方法字段中显示的选择字段

javascript - JS 正则表达式 : strings to JSON object

java正则表达式

python - 用正则表达式替换所有非字母/数字

javascript - VueJS2:如果值相同,则复选框和切换元素可见性

javascript - 为什么这个正则表达式匹配?