December 2023
Intermediate to advanced
242 pages
5h 28m
English
| Recipe 45 | Modifying an Existing Regex Literal |
Suppose you want to take your teammate’s regular expression literal and modify it for use in another part of the code. You don’t want to alter the original regex because it has passed all tests for the job it was intended for.
You need a solution that enables you to modify a copy of an existing regex literal.
Use the source and flags properties to retrieve the original regex parts. And construct a new RegExp object with those parts:
| | // Pattern to match a filename with .png extension |
| | const origRegex = /\b(\w+)\.png\b/; |
| | |
| | // Pattern to match a filename with .png or .PNG extension |
| | const newRegex = new RegExp(origRegex.source, ... |
Read now
Unlock full access