How do you clone a regular expression in JavaScript? I would like to know how to do the following:
lastIndex
("shallow" clone).lastIndex
("deep" clone).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;