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?
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
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
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
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
const patterns = [/^\d+$/, /[A-Z]/, /\s/];
const input = "Test 123";
patterns.forEach(p => console.log(p, p.test(input)));
Chapter Quiz — Complete all 26 topics to unlock
0/26 topics done
Complete these topics first:
- JS JSON
- JS Regular Expressions
- JS Fetch API
- JS LocalStorage and SessionStorage
- JS Cookies
- JS setTimeout and setInterval
- JS Event Loop
- JS Web Workers
- JS Service Workers
- JS AJAX
- JS AJAX Intro
- JS AJAX XMLHttp
- JS AJAX Request
- JS AJAX Response
- JS AJAX XML
- JS AJAX PHP
- JS AJAX Database
- JS JSONP
- JS RegExp Flags
- JS RegExp Classes
- JS RegExp Metachars
- JS RegExp Assertions
- JS RegExp Groups
- JS RegExp Quantifiers
- JS JSON HTML
- JS JSON vs XML