Regular Expressions in JavaScript a Complete Primer
A working primer on JavaScript regular expressions: syntax, flags, match and matchAll, named groups, lookarounds, replace and the global flag state trap.

A regular expression is a small language for describing text, and it earns its place wherever a task is "find this shape in a string": validate an id, pull numbers out of a log line, rewrite a template. It also has more sharp edges than most of JavaScript, and a handful of them cause most of the questions. A test() that returns true and then false on the same input. A greedy match that swallows too much. A pattern copied from a forum that takes ten seconds on a long string. This primer covers the syntax you will use daily, the methods and the flags, then the traps, with output from Node.js 24 as an ES module. The strings these patterns run on are UTF-16, which matters for the u flag and is covered in the post on UTF-16 strings, and the wider tour of the language is in the guide to modern JavaScript.
Creating a regex and testing it
A literal sits between slashes, with flags after the closing slash. test() returns whether the pattern matches anywhere in the string.
const digits = /\d+/;
const fromString = new RegExp("\\d+");
console.log(digits.test("order 42"), digits.test("no digits"));
console.log(digits.source, digits.flags === "", fromString.source);
console.log(/^\d+$/.test("42"), /^\d+$/.test("42 apples"));
console.log(/colou?r/i.test("COLOR"), /colou?r/i.test("colour"));true false
\d+ true \d+
true false
true trueWithout anchors, a pattern matches anywhere in the string, so /\d+/ found the digits inside "order 42". The anchors ^ and $ pin the match to the start and the end, which is how a full-string validation is written. A ? makes the previous character optional and the i flag ignores case. In new RegExp("\\d+") the backslash is doubled, because the string literal consumes one level of escaping before the regex sees it.
Getting the matched text
match() returns the match with its groups, and with the g flag it returns only the matched strings. matchAll() returns an iterator of full match objects for every match.
const log = "GET /a 200, POST /b 404, GET /c 500";
console.log(log.match(/\d{3}/));
console.log(log.match(/\d{3}/g));
console.log(log.match(/nope/), log.match(/nope/g));
const request = /(?<method>GET|POST) (?<path>\/\w+) (?<status>\d{3})/g;
for (const match of log.matchAll(request)) {
const { method, path, status } = match.groups;
console.log(method, path, status, match.index);
}
const [, first] = /(\d+)-(\d+)/.exec("range 10-20") ?? [];
console.log(first);[
'200',
index: 7,
input: 'GET /a 200, POST /b 404, GET /c 500',
groups: undefined
]
[ '200', '404', '500' ]
null null
GET /a 200 0
POST /b 404 12
GET /c 500 25
10Without g, the first match carries its position and groups. With g, only the matched strings come back, and no match gives null, or null again for the global form, which is why the result needs a guard. matchAll requires the g flag and yields each match with groups, here read through destructuring. Named groups, written (?<name>...), make the code say what was captured, and they are far easier to maintain than numbered ones. Plain exec() returns an array with the groups at numbered positions.
The global flag keeps state
A regex with g or y remembers where its last match ended in lastIndex. Each test() or exec() call starts from there, and a regex stored in a variable and reused can skip matches.
const shared = /a/g;
console.log(shared.test("a"), shared.lastIndex);
console.log(shared.test("a"), shared.lastIndex);
console.log(shared.test("a"), shared.lastIndex);
const fresh = /a/;
console.log(fresh.test("a"), fresh.test("a"));
const ids = ["a1", "a2", "a3"];
const matcher = /a\d/g;
console.log(ids.filter((id) => matcher.test(id)));
console.log(ids.filter((id) => /a\d/.test(id)));true 1
false 0
true 1
true true
[ 'a1', 'a3' ]
[ 'a1', 'a2', 'a3' ]The shared global regex returned true, then false, then true: after the first match lastIndex was 1, the second search started at the end of the string and failed, and failing reset it to zero. The same bug in the filter call dropped "a2" from the result, because every other call began from a stale index. Fixes are to avoid g when you only need test, to create the regex inside the function or to reset lastIndex = 0 before use. A regex literal inside a function body is created fresh on each call, which is why the last line works.
Greedy and lazy
Quantifiers such as *, + and {n,m} take as much as they can by default. Adding ? makes them take as little as the pattern allows.
const html = "<b>bold</b> and <i>italic</i>";
console.log(html.match(/<.+>/)[0]);
console.log(html.match(/<.+?>/)[0]);
console.log(html.match(/<[^>]+>/g));
const prices = "from $5 to $120";
console.log(prices.match(/\$\d+/g));
console.log("aaa".match(/a{2}/)[0], "aaa".match(/a{2,}/)[0], "aaa".match(/a{1,2}?/)[0]);<b>bold</b> and <i>italic</i>
<b>
[ '<b>', '</b>', '<i>', '</i>' ]
[ '$5', '$120' ]
aa aaa aThe greedy .+ ran to the last > in the string and matched almost everything. The lazy version stopped at the first one. A character class, [^>]+, that excludes the closing character is usually the best fix, since it states what is allowed and cannot overshoot. Do not try to parse HTML with regular expressions beyond a throwaway extraction, because the language of nested tags is not regular and a parser is the right tool.
Groups, alternation and backreferences
Parentheses capture, (?:...) groups without capturing, | chooses between alternatives and \1 or \k<name> refers back to an earlier group.
console.log("2026-05-06".match(/(\d{4})-(\d{2})-(\d{2})/).slice(1));
console.log("cat dog bird".match(/\b(?:cat|dog)\b/g));
console.log(/(\w)\1/.test("book"), /(\w)\1/.test("page"));
console.log("hello hello world".replace(/\b(?<word>\w+) \k<word>\b/, "$<word>"));
const indices = /a(b)/d.exec("xab");
console.log(indices.indices[1]);[ '2026', '05', '06' ]
[ 'cat', 'dog' ]
true false
hello world
[ 2, 3 ]The first line captured three numbers. The non-capturing group listed the alternatives without adding a capture. A backreference matched a repeated letter in "book" and found none in "page", and the same idea removed a doubled word through a named reference. The d flag adds an indices array with the start and end of each group, which helps when you need positions and not only text.
Lookahead and lookbehind
Lookarounds assert that something is, or is not, next to the current position, without consuming it.
const price = "cost: 15 USD, 20 EUR, 30 USD";
console.log(price.match(/\d+(?= USD)/g));
console.log(price.match(/\d+(?! USD)/g));
console.log(price.match(/(?<=cost: )\d+/g));
console.log("1234567".replace(/\B(?=(\d{3})+(?!\d))/g, ","));
console.log(/^(?=.*\d)(?=.*[a-z]).{8,}$/.test("passw0rdx"), /^(?=.*\d)(?=.*[a-z]).{8,}$/.test("password"));[ '15', '30' ]
[ '1', '20', '3' ]
[ '15' ]
1,234,567
true falseThe positive lookahead found numbers followed by a currency, and the negative form found the others, with a quirk: \d+(?! USD) can match a prefix of "15" when backtracking, so a negative lookahead on a variable-length match needs care. The lookbehind found the number after a label. The thousands separator pattern inserts commas at every position followed by groups of three digits, and the final line shows lookaheads used as independent conditions in a password check. For number formatting in real code, Intl.NumberFormat is more correct, as covered in the post on the Intl API.
Replace, split and the other string methods
replace() takes a string or a function as the replacement, and the patterns $1, $<name> and $& refer to matches.
console.log("2026-05-06".replace(/(\d+)-(\d+)-(\d+)/, "$3/$2/$1"));
console.log("a-b-c".replace("-", "+"), "a-b-c".replaceAll("-", "+"), "a-b-c".replace(/-/g, "+"));
console.log("price 5 and 7".replace(/\d+/g, (n) => String(Number(n) * 2)));
console.log("a1b22c333".split(/\d+/), "one two".split(/\s+/));
console.log("hello".search(/l+/), "hello".search(/z/));
console.log("Hello World".replace(/(?<first>\w+) (?<second>\w+)/, "$<second> $<first>"));06/05/2026
a+b-c a+b+c a+b+c
price 10 and 14
[ 'a', 'b', 'c', '' ] [ 'one', 'two' ]
2 -1
World HelloA string pattern replaces only the first occurrence, replaceAll() and the g flag replace every one, and a function replacement computes each result. split accepts a regex, and search returns an index or -1. These cover most day-to-day text work, and they all share the same engine.
Building a regex from user input
A pattern assembled from a variable must escape characters that have meaning in a regex, or a search for a.b also matches axb. RegExp.escape() is available in Node.js 24.
const query = "price (USD";
const unsafe = () => new RegExp(query);
try {
unsafe();
} catch (error) {
console.log(error.name);
}
const escaped = RegExp.escape("a.b*c");
console.log(escaped);
console.log(new RegExp(RegExp.escape(query)).test("the price (USD is 5"));
console.log(new RegExp("a.b").test("axb"), new RegExp(RegExp.escape("a.b")).test("axb"));SyntaxError
\x61\.b\*c
true
true falseWithout escaping, the unbalanced parenthesis was a SyntaxError, and the dot matched any character. RegExp.escape() returned a string safe to embed. Its output looks odd, since a leading letter or digit is written as a hex escape, \x61 for a, so the result can be placed after another escape without merging into it, and the dot and star are escaped with backslashes. On older runtimes, a one-line replace of the special characters does the same job.
Catastrophic backtracking
A pattern with nested quantifiers over overlapping input can take exponential time on a string that almost matches. A server that runs such a pattern on user input can be stalled by a short crafted string, a denial of service known as ReDoS.
const risky = /^(a+)+$/;
const safe = /^a+$/;
const input = "a".repeat(24) + "!";
console.log(safe.test(input));
console.log(risky.test("a".repeat(10)));false
trueThe safe pattern rejects the long string at once. The risky one is fine on a matching string, and the failing input of 24 characters followed by a mismatch would make it try an exponential number of splits, so the demonstration runs only the safe case on it. Avoid nested quantifiers like (a+)+, prefer specific character classes, cap input length before matching and consider a linear-time engine for patterns that must accept untrusted input. A length limit is the cheapest defense, and the post on the includes() method shows a plain-string alternative when you only need to find a fixed substring.
Unicode and the u flag
Without u, a pattern sees UTF-16 code units. With u, it sees code points and supports property escapes.
console.log(/^.$/.test("😀"), /^.$/u.test("😀"));
console.log("naïve café".match(/\p{L}+/gu));
console.log(/\p{Emoji_Presentation}/u.test("hi 😀"));
console.log("ÀB".match(/[\p{Lu}]/gu));false true
[ 'naïve', 'café' ]
true
[ 'À', 'B' ]The dot matched the emoji only in Unicode mode. \p{L} matches letters in any script, which \w does not, since \w is ASCII only. The v flag extends this with set operations, and it is available in current engines.
Where regex stops being the right tool
Use a regex for a bounded, regular shape: an identifier, a number, a simple token. Use a parser for nested structure such as HTML, JSON or code, a validator library for emails and URLs, whose real grammars are complex, and Intl for locale-aware formatting. And keep complex patterns readable: split them into named parts, comment them and test them against a table of positive and negative cases.
The syntax is defined in the specification under regular expressions, and MDN's regular expressions guide covers the full syntax.


