JavaScript RegExp Literals and Constructors
Quick answer
A regular expression describes a pattern to match against text. Use a literal for a fixed pattern or the RegExp constructor for a pattern selected at runtime.
How it works
/pattern/flags is a literal; new RegExp(pattern, flags) accepts a string or regex. A string passed to the constructor has already undergone string escaping, so a regex backslash typically needs a doubled backslash in source. test returns a Boolean; exec returns match information or null. Use fixed patterns for untrusted input.
console.log(/cat/.test("catalog"), /cat/.test("dog"));Expected output in Node.js:
true falseAn unanchored pattern can match a substring.
const pattern = new RegExp("\\d+");console.log(pattern.exec("ID42")[0]);Expected output in Node.js:
42String escaping leaves a single regex backslash before d.
Common mistakes
A regex need not match the whole input. For validation use explicit boundaries and a stated input contract.
Practice
Compare matching an identifier inside a longer string with a whole-string validation requirement.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript RegExp Literals and Constructors — Knowledge Check
Apply the taught concept and predict the output.
When is the RegExp constructor especially useful?
What does test return?
What does exec return when no match exists?
What is the exact console output in JavaScript RegExp Literals and Constructors example 1?
console.log(/cat/.test("catalog"), /cat/.test("dog"));What is the exact console output in JavaScript RegExp Literals and Constructors example 2?
const pattern = new RegExp("\\d+");console.log(pattern.exec("ID42")[0]);