A regular expression is compiled when it is created: the JavaScript engine parses it and converts it to an internal representation. Matching is a separate execution phase. section 10.3
Avoid needless compilation when a pattern is reused:
- Create a regex once and store it for later use. Browsers may cache identical patterns, but don’t rely on that, especially for complex expressions. section 10.3
- Use a literal for a fixed pattern or a RegExp constructor when the pattern must be built from a runtime string. section 10.3
Listing 10.2. Two ways to create a compiled regular expression
const re1 = /test/i; #A
const re2 = new RegExp("test", "i"); #B
assert(re1.toString()=== "/test/i",
"Verify the contents of the expression.");
assert(re1.test("TesT"), "Yes, it's case-insensitive.");
assert(re2.test("TesT"), "This one is too.");
assert(re1.toString()=== re2.toString(),
"The regular expressions are equal.");
assert(re1 !== re2, "But they are different objects.");
Compare literal and constructor forms; both create compiled regexes, but each creates a distinct object. section 10.3






