javascriptregexclone

How do you clone a RegExp object?


How do you clone a regular expression in JavaScript? I would like to know how to do the following:

  1. Clone the regex itself, not including state properties like lastIndex ("shallow" clone).
  2. Clone the regex object, including state properties like lastIndex ("deep" clone).

Solution

  • Shallow clone the regex itself, not including properties like lastIndex.

    A regular expression consists of a pattern and flags.

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

    Deep clone the regex object, including properties like lastIndex.

    lastIndex is the only state.

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