JavaScript Tutorial · JavaScript Toolbox · Lesson 38 of 44
JavaScript Regular Expressions
Match, test, extract and replace text with regular expressions.
Creating a regex
A regular expression describes a text pattern. Write it between slashes, with optional flags after: /pattern/flags.
| Flag | Meaning |
|---|---|
g |
global — find all matches |
i |
case-insensitive |
m |
^ and $ match at line breaks |
Common tokens
| Token | Matches |
|---|---|
\d \w \s |
digit, word character, whitespace |
. |
any character except newline |
+ * ? {2,4} |
one or more, zero or more, optional, 2–4 times |
[abc] [^abc] |
any of / none of these characters |
^ $ |
start / end of the string |
( ) (?<name> ) |
capture group / named group |
Testing and matching
const zip = /^\d{5}$/;
console.log(zip.test("90210"), zip.test("9021"));
const text = "Call 555-1234 or 555-9876 today";
console.log(text.match(/\d{3}-\d{4}/g));
const m = "2026-10-12".match(/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/);
console.log(m.groups.year, m.groups.month, m.groups.day);
Output
true false [ '555-1234', '555-9876' ] 2026 10 12
Replacing
console.log("a b c".replace(/\s+/g, " "));
console.log("Hello World".replace(/o/g, "0"));
console.log("2026-10-12".replace(/(\d+)-(\d+)-(\d+)/, "$3/$2/$1"));
const slug = " Hello, World! JS Tips ".trim().toLowerCase().replace(/[^a-z0-9]+/g, "-");
console.log(slug);
Output
a b c Hell0 W0rld 12/10/2026 hello-world-js-tips
Test yourself
Which flag makes a regex find every match instead of only the first?
agim
Show answer
Answer: g
Practice next
- Valid Palindrome · coding problem
- Slugify a Title (Strings & Regex) · coding problem