Ad space (banner)
🟨JavaScript Lessons
Lesson 33 / 69

Introduction to Regular Expressions (Pattern Matching)

In this lesson you'll learn the basics of regular expressions in JavaScript so you can validate and extract strings that follow a pattern, like an email address or a phone number. This is for people searching "JavaScript regex usage" or "JavaScript match vs test."

A regular expression is a special notation for representing the "shape" of a string. It lets you specify a pattern — like "a ZIP code is 3 digits, a hyphen, then 4 digits" — and check whether a string matches it, or extract the matching part. You write it as /pattern/, and you can get a true/false result for whether it matches with .test(), or get the matched substring with .match().

The sample code uses a phone-number pattern, /\d{3}-\d{4}-\d{4}/, to pull just the phone number out of a sentence with .match(). \d means "one digit character," and {3} means "repeat the previous thing 3 times." Using .test(), /^\d+$/.test("12345") checks whether the entire string consists only of digits.

It can feel intimidating at first with all the symbols, but it's an extremely powerful tool in real projects — for checking the format of an email address, or extracting just the information you need from a body of text. A common beginner stumbling block is that symbols like . and * each have a special meaning ("metacharacters") — if you want to match them as literal characters, you need to escape them with a backslash.

In real development, regular expressions are used in an extremely wide range of situations: validating form input (checking the format of an email address or password), extracting specific patterns from a log file, and bulk text replacement. As you get gradually more comfortable with the notation, even complex string processing becomes achievable in surprisingly short code.

JavaScript
OUTPUT

💡 Anything passed to console.log() appears in the output below.

Ad space (banner)
Ad space (in-article)