The JavaScript RegExp object
A RegExp (regular expression) describes a text pattern for searching, validating or replacing. Write one as a literal between slashes — /\d+/g — with optional flags like g (global) and i (case-insensitive). Test with regex.test(str), and use it with match(), replace() and split().
Overview
A regular expression is a compact pattern that matches text. You most often write one as a literal between slashes — /cat/, /\\d{3}/, /^[a-z]+$/ — optionally followed by flags. The other form, new RegExp("pattern", "flags"), builds one from a string, which is what you need when the pattern is dynamic. The literal form is preferred when the pattern is fixed.
Flags change how matching works. g finds all matches (not just the first), i is case-insensitive, m makes ^ and $ match per line, and s lets . match newlines. Patterns themselves use a rich syntax: character classes (\\d digit, \\w word, \\s whitespace), quantifiers (+, *, {2,4}), anchors (^ start, $ end), groups ((...)) and alternation (a|b).
You use a regex in two ways: its own methods, and string methods that accept one. regex.test(str) returns a quick true/false (perfect for validation), and regex.exec(str) returns match details. On the string side, match() and matchAll() extract matches, replace() swaps them, and split() can split on one. Regex is powerful but easy to overdo — for simple substring checks, includes() is plenty.
Syntax
const re = /\d+/g; // literal
const re2 = new RegExp("\\d+", "g"); // from a string
re.test("abc123"); // true
"a1b2".match(/\d/g); // ["1", "2"]
"a-b-c".replace(/-/g, "+"); // "a+b+c"
Example
<pre id="out" style="font:15px ui-monospace,monospace"></pre>
<script>
const emailRe = /^[^@\s]+@[^@\s]+\.[^@\s]+$/;
const inputs = ['ada@example.com', 'not-an-email'];
const lines = inputs.map(v => v + ' -> ' + emailRe.test(v));
document.getElementById('out').textContent = lines.join('\n');
// ada@example.com -> true / not-an-email -> false
</script>
Best practices
- Use a literal
/pattern/for fixed patterns; usenew RegExp()only when the pattern is dynamic. - Use
regex.test(str)for simple yes/no validation. - Add the
gflag to match every occurrence,ifor case-insensitive. - Don't reach for regex when includes() or startsWith() would do — keep it simple.
Frequently asked questions
How do I create a regular expression in JavaScript?
/\d+/g, or build one from a string with new RegExp("\\d+", "g").How do I test if a string matches a pattern?
regex.test(str), which returns true or false.What do the regex flags mean?
g matches all occurrences, i ignores case, m is multiline, and s lets . match newlines.