← Back to JavaScript Course | Chapter 9: Async & Web APIs | Lesson 2 of 26

JS Regular Expressions

What Is Regex?

A regular expression is a pattern used to find or check text. Patterns are written between slashes, like /abc/, and can include flags such as g (global) or i (case-insensitive) that change how the match behaves.

Example: What Is Regex?

javascript
const pattern = /abc/i;
console.log(pattern.test("ABC123")); // true, case-insensitive flag

Regex Methods

JavaScript provides test() and match() for working with regular expressions. test() returns a boolean indicating whether the pattern matches anywhere in the string, while match() returns the actual matched substring(s) or null if nothing matched.

Example: Regex Methods

javascript
const pattern = /cat/;
console.log(pattern.test("I have a cat"));
console.log("I have a cat".match(pattern));

Common Patterns

Character classes and quantifiers help create useful text patterns. Character classes like [a-z] match any character in a range, and quantifiers like + or {2,4} control how many times the preceding piece can repeat.

Example: Common Patterns

javascript
const pattern = /[a-z]+\d{2,4}/;
console.log(pattern.test("abc123"));

Replace With Regex

replace() can use a regular expression to change matching text. Passing a regex (instead of a plain string) to replace() lets you substitute every match at once when the g flag is set, rather than only the first occurrence.

Example: Replace With Regex

javascript
const text = "cat cat cat";
console.log(text.replace(/cat/g, "dog"));

Practice Patterns

Start with simple patterns and test different inputs. Regex syntax is dense, so building patterns incrementally against real sample strings — rather than writing the whole pattern blind — makes mistakes much easier to catch.

Example: Practice Patterns

javascript
const patterns = [/^\d+$/, /[A-Z]/, /\s/];
const input = "Test 123";
patterns.forEach(p => console.log(p, p.test(input)));

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.