JavaScript Regular Expressions: Literals, Character Classes, Quantifiers, Anchors and Groups
Learn to read and write regular expressions: regex literals vs new RegExp, escaping, character classes and shorthand like \d \w \s, Unicode property escapes, quantifiers and greedy vs lazy matching, alternation, capturing and named groups, backreferences, anchors, word boundaries and lookarounds.
kvi5hnuCode Sprout team member8 min readOn this page
A regular expression (regex) describes a pattern of text: "a date like 2026-11-18", "a word repeated twice", "every price in dollars". With one pattern you can test whether text matches, find all matches, extract pieces, or replace them. Regexes are a small language of their own, shared (with dialect differences) by almost every programming language, editor, database and command-line tool, so time spent learning them pays off everywhere.
This article covers the pattern syntax. The next article covers flags and the JavaScript methods that use regexes, and the one after that covers advanced features, practical recipes and performance.
Creating a regex
const literal = /colou?r/i; // between slashes, flags after
const built = new RegExp("colou?r", "i"); // from a string (pattern, flags)
console.log(literal.test("COLOR"), built.test("Colour"), literal.source, literal.flags);
const word = "cat";
const dynamic = new RegExp(`^${word}s?$`); // built from a variable at runtime
console.log(dynamic.test("cats"), dynamic.test("concat"));
true true colou?r i
true false
- Use a literal
/.../flagswhen the pattern is fixed: it's checked when the code is parsed, and you don't need extra escaping. - Use
new RegExp(string, flags)when the pattern is built at runtime. Inside a string, every regex backslash must be doubled: the regex\d+is writtennew RegExp("\\d+"), because"\d"in a string is just"d". test(string)returnstrueif the pattern matches anywhere in the string (unless you anchor it, below).
Literal characters and escaping
Letters, digits and most characters match themselves: /cat/ matches "cat" inside "concatenate". These characters have special meanings and must be escaped with a backslash to match literally:
^ $ \ . * + ? ( ) [ ] { } | /
console.log("a.b".replace(/./g, "x")); // . means "any character"
console.log("a.b".replace(/\./g, "x")); // \. means a literal dot
console.log("Total: $4.99".match(/\$\d+\.\d\d/)[0]);
xxx
axb
$4.99
Special escapes for invisible characters work as in strings: \n (newline), \t (tab), \r, \0, \xHH, \uHHHH, and \u{1F600} (with the u flag). When the text to match comes from users, escape it automatically with RegExp.escape(text) (ES2025; article 82).
Character classes
Square brackets match one character from a set:
| Pattern | Matches |
|---|---|
[aeiou] | any one vowel |
[a-z], [A-Za-z0-9] | one character in a range |
[^0-9] | any one character except a digit (^ first means "not") |
[-a-z] or [a-z-] | a hyphen goes first or last to be literal |
[.*+] | most special characters are literal inside brackets |
console.log("gray grey griy".match(/gr[ae]y/g));
console.log("a1 b2 c3".match(/[^a-c\s]/g));
console.log("user-name_42".match(/[\w-]+/)[0]);
[ 'gray', 'grey' ]
[ '1', '2', '3' ]
user-name_42
Shorthand classes
| Shorthand | Meaning | Opposite |
|---|---|---|
\d | a digit [0-9] | \D |
\w | a "word" character [A-Za-z0-9_] | \W |
\s | whitespace: space, tab, newline, and Unicode spaces | \S |
. | any character except line terminators (unless the s flag is set) |
console.log("Room 42B, floor 7".match(/\d/g));
console.log("café crème".match(/\w+/g));
console.log("a\nb".match(/a.b/), "a\nb".match(/a.b/s)[0].length);
[ '4', '2', '7' ]
[ 'caf', 'cr', 'me' ]
null 3
\w and \d are ASCII only: "é" and "è" aren't word characters. For real-world text in any language, use Unicode property escapes.
Unicode property escapes
With the u (or v) flag, \p{...} matches characters by Unicode property, and \P{...} matches the opposite:
console.log("café naïve straße".match(/\p{L}+/gu)); // L = any letter
console.log("ÅbΩc".match(/\p{Lu}/gu)); // Lu = uppercase letter
console.log("Price ٣٤ or 42".match(/\p{Nd}+/gu)); // Nd = decimal digits in any script
console.log("Hi 😀!".match(/\p{Emoji_Presentation}/u)[0]);
console.log("Привет".match(/\p{Script=Cyrillic}+/u)[0]);
[ 'café', 'naïve', 'straße' ]
[ 'Å', 'Ω' ]
[ '٣٤', '42' ]
😀
Привет
Common properties: L (letter), Lu/Ll (upper/lowercase letter), N (number), P (punctuation), S (symbol), Script=Greek, Emoji. The u flag also makes . and classes treat emoji and other astral characters as single characters instead of two UTF-16 halves (article 14).
Quantifiers: how many times
A quantifier applies to the item just before it (a character, class or group):
| Quantifier | Meaning |
|---|---|
* | 0 or more |
+ | 1 or more |
? | 0 or 1 (optional) |
{n} | exactly n |
{n,} | n or more |
{n,m} | between n and m |
console.log("color colour".match(/colou?r/g));
console.log("Call 555-0142 or 555-9876".match(/\d{3}-\d{4}/g));
console.log("hmm hmmmm hm".match(/hm{2,}/g));
console.log("aaaa".match(/a{2,3}/)[0]);
[ 'color', 'colour' ]
[ '555-0142', '555-9876' ]
[ 'hmm', 'hmmmm' ]
aaa
Greedy vs lazy
Quantifiers are greedy by default: they match as much as possible while still allowing the overall match to succeed. Adding ? makes them lazy (match as little as possible):
const html = "<b>bold</b> and <b>more</b>";
console.log(html.match(/<b>.*<\/b>/)[0]); // greedy: runs to the LAST </b>
console.log(html.match(/<b>.*?<\/b>/)[0]); // lazy: stops at the first </b>
console.log(html.match(/<b>[^<]*<\/b>/g)); // often better: say what's allowed
<b>bold</b> and <b>more</b>
<b>bold</b>
[ '<b>bold</b>', '<b>more</b>' ]
The lazy forms are *?, +?, ?? and {n,m}?. A negated class like [^<]* is often clearer and faster than a lazy .*?, because it can't run past the delimiter. (For real HTML, use a parser such as DOMParser, not regexes.)
Alternation: this or that
| matches either the pattern on its left or on its right. It has the lowest precedence, so it splits the whole regex (or the enclosing group):
console.log("cat dog bird".match(/cat|dog/g));
console.log(/^cat|dog$/.test("catfish")); // means (^cat) OR (dog$)
console.log(/^(?:cat|dog)$/.test("catfish")); // the whole string must be cat or dog
[ 'cat', 'dog' ]
true
false
Alternatives are tried left to right, and the first that leads to an overall match wins, so /Java|JavaScript/ matches only "Java" in "JavaScript". Put longer alternatives first, or add a boundary.
Groups
Parentheses group items so a quantifier or alternation applies to all of them. They also capture the matched text:
const m = "Released 2026-11-18".match(/(\d{4})-(\d{2})-(\d{2})/);
console.log(m[0], m[1], m[2], m[3], m.index);
console.log("ababab!".match(/(?:ab)+/)[0]); // non-capturing group: grouping only
2026-11-18 2026 11 18 9
ababab
( ... )captures: the matched text is available asm[1],m[2]... numbered by the position of the opening parenthesis.(?: ... )groups without capturing. Use it when you only need grouping; it keeps the numbering simple.- A group that didn't take part in the match gives
undefined.
Named groups
(?<name> ... ) gives a group a name, available on match.groups. Named groups make patterns self-documenting and don't break when you add another group:
const date = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;
const { year, month, day } = "Due 2027-01-05".match(date).groups;
console.log(year, month, day);
console.log("2027-01-05".replace(date, "$<day>/$<month>/$<year>"));
2027 01 05
05/01/2027
Backreferences
Inside the pattern, \1, \2... (or \k<name>) match the same text a group already captured:
console.log("this is is a test".match(/\b(\w+) \1\b/)[0]);
console.log(`say 'hi' or "yo"`.match(/(['"]).*?\1/g));
console.log(/(?<q>['"]).*\k<q>/.test(`'mismatched"`));
is is
[ "'hi'", '"yo"' ]
false
The second example matches quotes that open and close with the same character.
Anchors and boundaries
Anchors match positions, not characters:
| Anchor | Matches the position... |
|---|---|
^ | at the start of the input (or of each line, with m) |
$ | at the end of the input (or of each line, with m) |
\b | between a word character and a non-word character (or the edge) |
\B | anywhere that isn't a word boundary |
const isZip = /^\d{5}$/; // the WHOLE string must be 5 digits
console.log(isZip.test("90210"), isZip.test("90210-1234"), /\d{5}/.test("x90210x"));
console.log("one subtwo two".match(/\btwo\b/).index);
console.log("cat category concat".match(/\bcat\w*/g));
true false true
11
[ 'cat', 'category' ]
Validation patterns almost always need ^ and $; without them, /\d{5}/ happily accepts "abc123456def". Remember that \b uses the ASCII definition of \w, so it misbehaves next to accented letters.
Lookahead and lookbehind
Lookarounds check what comes before or after a position without consuming it (the checked text isn't part of the match):
| Syntax | Name | Succeeds if... |
|---|---|---|
X(?=Y) | lookahead | X is followed by Y |
X(?!Y) | negative lookahead | X is not followed by Y |
(?<=Y)X | lookbehind | X is preceded by Y |
(?<!Y)X | negative lookbehind | X is not preceded by Y |
console.log("100px 2em 300px".match(/\d+(?=px)/g)); // numbers followed by px
console.log("$5 €6 $7".match(/(?<=\$)\d+/g)); // amounts after $
console.log("$5 €6 $7".match(/(?<!\$)\b\d+/g)); // amounts NOT after $
console.log("1234567.891".replace(/\B(?=(\d{3})+(?!\d))/g, ","));
[ '100', '300' ]
[ '5', '7' ]
[ '6' ]
1,234,567.891
The last line inserts thousands separators: at every non-boundary position followed by groups of three digits and then no more digits. Lookarounds are also useful for password-style rules (^(?=.*\d)(?=.*[a-z]).{8,}$: "contains a digit and a lowercase letter, and is at least 8 characters"). For formatting real numbers, though, Intl.NumberFormat (article 85) is the right tool.

Reading a regex
Long patterns are easier to read piece by piece. Take /^(?<user>[\w.+-]+)@(?<domain>[\w-]+(?:\.[\w-]+)+)$/:
^...$: the whole string must match.(?<user>[\w.+-]+): one or more word characters, dots, pluses or hyphens, captured asuser.@: a literal at sign.(?<domain>[\w-]+(?:\.[\w-]+)+): a label, then one or more.labelparts, captured asdomain.
It's a reasonable "looks like an email address" check, not a full validator. Tools like regex101.com (with the JavaScript flavor selected) explain each part, show matches live, and are worth bookmarking.
Common questions
Why does my new RegExp("\d+") match the letter d?
In a string literal, \d isn't a recognized escape, so it becomes just "d". Double the backslash: new RegExp("\\d+"), or use a regex literal /\d+/.
What's the difference between [abc] and (a|b|c)?
They match the same single characters, but the class is simpler and faster and doesn't capture. Use alternation for multi-character alternatives like (cat|dog).
Why didn't ^ and $ match at each line?
By default they match only at the very start and end of the input. Add the m (multiline) flag to make them match at line breaks too (next article).
Are regexes case-sensitive?
Yes, by default. Add the i flag (/hello/i) for case-insensitive matching.
Summary
- Write fixed patterns as
/literals/flags; build dynamic ones withnew RegExp(string, flags), doubling backslashes. - Escape
^ $ \ . * + ? ( ) [ ] { } | /to match them literally. [...]matches one character from a set,[^...]one outside it;\d \w \sare ASCII shorthands,\p{...}withuhandles all of Unicode;.excludes newlines withouts.- Quantifiers
* + ? {n,m}are greedy; add?for lazy; prefer negated classes when possible. |has the lowest precedence;( )captures,(?: )groups only,(?<name> )captures by name;\1and\k<name>reuse captured text.^,$,\band lookarounds(?=) (?!) (?<=) (?<!)match positions; validation needs^...$.
Practice Questions
Write a regex that matches a whole string that is a hex color like #1a2B3c or #fff.
Answer
/^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i. The anchors require the whole string, and the group allows exactly 3 or 6 hex digits.
What does "aaa".match(/a+?/)[0] return, and why?
Answer
"a". The lazy quantifier +? matches as few characters as possible, which is one.
Why does /^\d+|[a-z]+$/.test("x9 abc") return true?
Answer
| splits the entire pattern into ^\d+ or [a-z]+$. The first alternative fails (the string doesn't start with a digit), but the second matches "abc" at the end. Wrap the alternation in a group, /^(?:\d+|[a-z]+)$/, to apply both anchors to both alternatives.
Extract all hashtags (like #js or #ES2026) from a tweet.
Answer
text.match(/#\w+/g), or /#[\p{L}\p{N}_]+/gu to include hashtags with non-English letters.
Previous: Typed Arrays, ArrayBuffer and DataView: Working with Binary Data in JavaScript
Next: JavaScript Regex Flags and Methods: test, exec, match, matchAll, replace, split and lastIndex

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.