Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do you clone a regular expression?

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

  1. Shallow clone the regex itself, not including state properties like lastIndex.
  2. Deep clone the regex object, including state properties like lastIndex.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading