← Back to JavaScript, page 3

javascript-0053 · Easy fresher

How do regular expressions work in JavaScript, and what are the common traps with the g flag and capture groups?

A regular expression describes a text pattern. test checks for a match, match and matchAll return matches, and replace rewrites them, with parentheses capturing parts and named groups giving them labels. A regex with the g flag keeps a lastIndex between calls, so reusing one with test or exec can skip matches.

Full answer

A regular expression, or regex, is a pattern that describes text. It is written between slashes, /pattern/flags, or created with new RegExp('pattern', 'flags'). Characters match themselves. Special pieces add power: \d is a digit, \w a letter, digit, or underscore, . any character except a line break, + one or more, * zero or more, ? optional, and ^ and $ mark the start and end.

Methods you need: regex.test(text) returns a boolean. text.match(regex) returns the first match with details, or all matches as plain strings when the g flag is set. text.matchAll(regex) returns an iterator with full details for each match and requires the g flag. text.replace(regex, replacement) rewrites matches, and the replacement can be a function.

Parentheses create capture groups. In /(\d{4})-(\d{2})/ the groups are numbered, and (?<year>\d{4}) gives a name that appears under match.groups. A group that does not match is undefined. Use (?:...) when grouping is needed without capturing.

Common flags: g global, i ignore case, m multiline anchors, s dot matches newlines, u Unicode mode, and y sticky.

The main trap is state. A regex with g or y remembers lastIndex, and test or exec starts from it. Calling test twice on the same global regex with the same text can return true and then false. Create the regex inside the function or avoid g with test.

Another warning: nested quantifiers such as (a+)+ can take exponential time on some inputs. Do not run untrusted patterns or inputs through such expressions.

javascript
const date = '2026-03-14';
const pattern = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;
const match = date.match(pattern);
console.log(match.groups.year, match.groups.month, match[3]);

const text = 'Call 98765 or 91234 now';
console.log(text.match(/\d{5}/g));
console.log([...text.matchAll(/(\d)(\d{4})/g)].map((m) => [m[0], m.index]));
console.log(text.replace(/\d{5}/g, (digits) => digits.slice(0, 2) + '***'));
console.log('2026-03-14'.replace(pattern, '$<day>/$<month>/$<year>'));

const globalRegex = /cat/g;
console.log(globalRegex.test('cat'), globalRegex.lastIndex);
console.log(globalRegex.test('cat'), globalRegex.lastIndex); // starts after the first match

const safeRegex = /cat/;
console.log(safeRegex.test('cat'), safeRegex.test('cat'));

console.log(/^[\w.+-]+@[\w-]+\.[\w.]+$/.test('asha@example.com'), /^[\w.+-]+@[\w-]+\.[\w.]+$/.test('no-at-sign'));
console.log('Hello'.match(/(x)?ello/)[1], /colou?r/i.test('COLOR'));
console.log('a\nb'.match(/a.b/), 'a\nb'.match(/a.b/s)?.[0]);

Run with Node.js v24.22.1 as js-53.js; two runs gave identical output. Output: 2026 03 14 [ '98765', '91234' ] [ [ '98765', 5 ], [ '91234', 14 ] ] Call 98*** or 91*** now 14/03/2026 true 3 false 0 true true true false undefined true null a b

Key points

  • Know the core pieces: \d, \w, ., +, *, ?, ^, $, and groups.
  • test returns a boolean; match, matchAll, and replace return details or new text.
  • Named groups appear in match.groups; non-participating groups are undefined.
  • Regex with g or y keeps lastIndex, which can make repeated test calls inconsistent.
  • Avoid nested quantifiers on untrusted input to prevent catastrophic backtracking.

Common mistakes

  • Reusing a global regex object with test and getting alternating results.
  • Using a simple regex to fully validate an email address; a basic check plus a confirmation message is more reliable.
  • Forgetting to escape special characters such as . or ( when they should match literally.
  • Using nested quantifiers on untrusted input and opening the door to catastrophic backtracking.

Follow-ups

  • What is the difference between greedy and lazy quantifiers?
  • How do lookahead and lookbehind assertions work?
  • What does the u flag change?

Tips

  • Show named groups and a replace callback; they signal current JavaScript knowledge.
  • Explain lastIndex whenever the g flag comes up.
  • Say that regexes are for pattern checks, and that parsers are better for HTML or nested structures.