JavaScript

Regex in JavaScript: RegExp, test, match, replace and Flags

JavaScript has built-in regular expression support. You can write a literal such as `/pattern/flags` or build a pattern dynamically with `new RegExp()`.

Before you start: test every pattern with examples that should match and examples that should fail.

Literal or RegExp constructor?

Use a literal when the pattern is known in the source code. Use new RegExp(text) when the pattern is built dynamically. Remember that backslashes inside JavaScript strings need an extra layer of escaping.

const re1 = /\d{3}/g;
const re2 = new RegExp('\\d{3}', 'g');

test() for a boolean answer

test() returns true or false and is ideal when you only need to know whether a value matches.

const email = /^[\w.-]+@[\w.-]+\.[A-Za-z]{2,}$/;
console.log(email.test('dev@example.com')); // true

match() and matchAll() for extraction

match() returns matches from a string. matchAll() is useful when you need multiple matches together with captured groups.

replace() for text transformation

Regex can also normalize text, remove repeated whitespace, or replace structured patterns.

'a   b'.replace(/\s+/g, ' '); // 'a b'

Common flags

g finds all occurrences, i ignores letter case, and m changes how anchors behave across multiple lines. Only enable flags that serve the requirement.

Next step: test it for real

Use the Playground to experiment with the pattern, then practice in the game with feedback on false positives and false negatives.

Practice in the gameTest in Playground

Keep learning

← Back to learning hub