C.W.K.
Stream
Lesson 05 of 10 · published

JavaScript RegExp Basics

~10 min · javascript, regexp

Level 0Pattern-Curious
0 XP0/90 lessons0/15 achievements
0/100 XP to next level100 XP to go0% complete

Two ways to create a regex

JavaScript has two regex syntaxes:

  • Literal: /pattern/flags — written between slashes, parsed at definition time. Faster, can't have embedded variables.
  • Constructor: new RegExp('pattern', 'flags') — a function call. Slower, but you can interpolate variables.

Use the literal form whenever the pattern is fixed. Use the constructor only when you need to build the pattern dynamically.

The methods

JavaScript splits regex methods between RegExp objects and String:

  • regex.test(str) — boolean: does it match?
  • regex.exec(str) — first match (or with /g flag, iterates).
  • str.match(regex) — first match, or all matches with /g flag.
  • str.matchAll(regex) — iterator of all matches (requires /g).
  • str.replace(regex, replacement) — replace first (or all with /g).
  • str.replaceAll(regex, replacement) — replace all (regex must have /g).
  • str.split(regex) — split.
  • str.search(regex) — index of first match, -1 if not found.

Quirks worth knowing

The /g flag is stateful. A regex with /g remembers lastIndex across exec calls. This causes "my regex matches the first time but not the second" bugs. matchAll is the modern, safer alternative.

Backslashes in constructor strings need doubling. new RegExp('\\d+'), not '\d+'. Same problem as Python without raw strings — and JavaScript has no raw string equivalent for regex.

Code

JavaScript regex usage·js
// Literal — preferred when pattern is fixed
const datePattern = /(\d{4})-(\d{2})-(\d{2})/;

const m = '2026-05-04'.match(datePattern);
// m[0] = '2026-05-04', m[1] = '2026', m[2] = '05', m[3] = '04'

// Constructor — when you need variables
const word = 'pippa';
const dynamic = new RegExp(`\\b${word}\\b`, 'i');
// note the \\b — backslashes doubled in the string

// test — boolean
/^foo/.test('foobar')  // true

// matchAll — modern, safe iteration
for (const m of 'a=1 b=2 c=3'.matchAll(/(\w+)=(\d+)/g)) {
  console.log(m[1], m[2]);
}
// a 1
// b 2
// c 3

// replaceAll requires /g
'a b c'.replaceAll(/\s/g, '_')  // 'a_b_c'

// Named groups (ES2018+)
const m2 = '2026-05-04'.match(/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/);
m2.groups  // { year: '2026', month: '05', day: '04' }

External links

Exercise

In the browser console, run the same /foo/g.exec('foofoo') call three times in a row. Note the changing lastIndex. Then do the same with matchAll — notice how the iteration is self-contained.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.