如何克隆 RegExp 对象? [已关闭]

问题描述 投票:0回答:1

如何在 JavaScript 中克隆正则表达式? 我想知道如何执行以下操作:

  1. 克隆正则表达式本身,不包括状态属性,如
    lastIndex
    (“浅”克隆)。
  2. 克隆正则表达式对象,包括状态属性,如
    lastIndex
    (“深度”克隆)。
javascript regex
1个回答
6
投票

浅克隆正则表达式本身,不包括像

lastIndex
这样的属性。

正则表达式由 patternflags 组成。

const copy = new RegExp(original.source, original.flags);

深度克隆正则表达式对象,包括

lastIndex
等属性。

lastIndex
是唯一的状态。

const copy = new RegExp(original.source, original.flags);
copy.lastIndex = original.lastIndex;
© www.soinside.com 2019 - 2024. All rights reserved.