iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

JS Regular Expressions

A regular expression is a tiny pattern language for matching strings. JavaScript writes them with /…/ literal syntax.

Anatomy

JS
/\d{3}-\d{4}/g
//  └─pattern─┘└─flags
//
// Flags
//   g  global — find all matches
//   i  case-insensitive
//   m  multi-line (^ and $ match line boundaries)
//   s  dotAll (. matches newlines)
//   u  unicode
//   y  sticky (match from lastIndex)

Common atoms

PatternMatches
.Any single character (except newline, unless s flag)
\d / \DDigit / non-digit
\w / \WWord char [A-Za-z0-9_] / non-word
\s / \SWhitespace / non-whitespace
[abc]Any of a, b, c
[^abc]Anything not a, b, c
^ / $Start / end of string (or line with m)
x?0 or 1 of x
x*0 or more
x+1 or more
x{3,5}3 to 5 of x
(abc)Capture group
(?:abc)Non-capturing group
(?<name>…)Named capture

Methods that use regex

JS
const re = /(\d{4})-(\d{2})-(\d{2})/;
"2026-06-06".match(re);              // ["2026-06-06", "2026", "06", "06", index: 0, ...]
re.test("2026-06-06");               // true

"a-b-c".replace(/-/g, "_");          // "a_b_c"
"a-b-c".split(/[-,]/);               // ["a", "b", "c"]

// Named captures
"2026-06-06".match(/(?<y>\d+)-(?<m>\d+)-(?<d>\d+)/).groups;
// { y: "2026", m: "06", d: "06" }
Tip: Don't try to parse HTML or email addresses with regex. The grammar of each is much hairier than it looks; use a real parser.

Example

Example
<!DOCTYPE html>
<html>
<body>

<p id="out"></p>

<script>
document.getElementById("out").textContent = "Hello from JS Regular Expressions!";
</script>

</body>
</html>
Try it Yourself »

Exercise

Add the flag that finds ALL matches, not just the first.

const re = /\d+/ ;

Test yourself

Q1. The `g` flag means…
Q2. `\d{3}-\d{4}` matches…
Q3. Test if a regex matches anywhere with…

Discussion

Loading…