How do you clone a regular expression in javascript?
I would like to know how to do the following:
- Shallow clone the regex itself, not including state properties like
lastIndex. - Deep clone the regex object, including state properties like
lastIndex.
>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;