How do you clone a regular expression in JavaScript?
I would like to know how to do the following:
- Clone the regex itself, not including state properties like
lastIndex
("shallow" clone). - Clone the regex object, including state properties like
lastIndex
("deep" clone).
2
Answers
A regular expression consists of a pattern and flags.
lastIndex
is the only state.The only state used in regular expressions is when the global flag (
g
) is used that allows for tracking what the last/next match of a regex should be:Clone without state
To clone the regular expression fully without the state (thus resetting the tracking), you only need to give the regex object to the
RegExp
constructor which will effectively copy the pattern and flagsSeen in action:
Note that you can also pass in flags which will override the previous flags:
This might be useful to force some flags on, if they are needed, regardless of where the pattern came from.
Clone with state
As Ry- points out the only state in an RegExp instance is
lastIndex
. This can be verified by usingReflect.ownKeys()
orObject.getOwnPropertyDescriptors()
In order to clone with state, it is enough to copy over the value of the
lastIndex
key: