Regular Expressions
Regular expressions (regex) are patterns for matching, searching, and replacing text. In JavaScript, create them with a literal /pattern/flags or new RegExp().
Regular expressions (regex) are patterns for matching, searching, and replacing text. In JavaScript, create them with a literal /pattern/flags or new RegExp().
// Literal syntax
const pattern = /hello/i;
// RegExp constructor (for dynamic patterns)
const word = "world";
const dynamic = new RegExp(`\b${word}\b`, "gi");
// Test if a pattern matches
/^\d{5}$/.test("90210"); // true (5-digit zip)
/^\d{5}$/.test("9021"); // false
Use the literal /pattern/ syntax by default — use new RegExp() only when the pattern is built dynamically.
More in JavaScript