Skip to main content
CodingMarble

Interview questions and cheat sheets

Regex Cheat Sheet With Practical JavaScript Patterns

A regular expression is a compact pattern that describes a set of strings, and in JavaScript you write it between slashes or build it with new RegExp. This sheet covers the syntax you use daily, six practical patterns that were run in Node with their results shown, and the failure modes that matter most: backtracking and false confidence in validation.

By CodingMarble · Published · 5 min read

Close-up of a computer keyboard
Photo: Christian Wiediger on Unsplash

Characters, classes and anchors

Most characters match themselves, so cat matches the text cat. A few characters carry special meaning and must be escaped with a backslash when you want them literally: . * + ? ^ $ ( ) [ ] { } | and the backslash itself. A character class in square brackets matches one character from a set, and a caret just inside the bracket negates it.

  • . matches any single character except a line break (unless the s flag is set).
  • \d is a digit, \w is a letter, digit or underscore, and \s is whitespace. Uppercase versions \D, \W and \S mean the opposite.
  • [abc] is one of a, b or c. [a-z] is a range. [^0-9] is any character that is not a digit.
  • ^ anchors to the start and $ to the end of the input (or of a line with the m flag). \b is a word boundary.
  • | means or, so cat|dog matches either word. Use a group to limit its reach.
JavaScript· Run in Node: classes and anchors
console.log("cat bat rat".match(/[cb]at/g));            // [ 'cat', 'bat' ]
console.log(/^\d{3}-\d{4}$/.test("555-1234"));            // true
console.log(/^\d{3}-\d{4}$/.test("55-1234"));             // false
console.log("a.b".replace(/./g, "x"));                    // xxx  (dot is any character)
console.log("a.b".replace(/\./g, "x"));                   // axb  (escaped dot is a literal dot)

Quantifiers: greedy and lazy

Quantifiers say how many times the previous item repeats: * is zero or more, + is one or more, ? is zero or one, {3} is exactly three, {2,5} is two to five and {2,} is two or more. By default they are greedy: they take as much text as they can and then give some back if the rest of the pattern fails. Adding a question mark after the quantifier makes it lazy, so it takes as little as possible.

The difference shows up whenever a delimiter appears more than once, as with HTML tags or quoted strings. A greedy .* runs to the last closing delimiter in the input, while a lazy .*? stops at the first. Often the clearest fix is neither: use a negated class such as [^<]* which cannot run past the delimiter at all and is also cheaper for the engine.

JavaScript· Run in Node: greedy versus lazy
const html = "<b>a</b> and <b>c</b>";
console.log(html.match(/<b>.*<\/b>/)[0]);     // <b>a</b> and <b>c</b>   (greedy)
console.log(html.match(/<b>.*?<\/b>/)[0]);    // <b>a</b>               (lazy)
console.log("a1b22c333".match(/\d+/g));       // [ '1', '22', '333' ]

Groups, named groups and lookarounds

Parentheses group part of a pattern so a quantifier or alternation applies to it, and they also capture the matched text. Capture groups are numbered from the left by opening parenthesis. A non-capturing group, (?:...), groups without capturing. Named groups, (?<year>...), give the capture a label, which is far easier to maintain than counting parentheses. In replacement strings you refer to them as $<name>.

JavaScript· Run in Node: named groups and reordering a date
const m = "2026-11-26".match(/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/);
console.log(m.groups.year, m.groups.month, m.groups.day);   // 2026 11 26

const swapped = "2026-11-26".replace(
  /(?<y>\d{4})-(?<m>\d{2})-(?<d>\d{2})/,
  "$<d>/$<m>/$<y>"
);
console.log(swapped);                                       // 26/11/2026

Lookarounds assert what comes next to, or before, the current position without consuming it. (?=x) is a positive lookahead, (?!x) a negative lookahead, (?<=x) a positive lookbehind and (?<!x) a negative lookbehind. Lookahead has long been supported everywhere. Lookbehind is newer in JavaScript, is available in current Chrome, Edge, Firefox, Safari and Node, but was missing from older Safari versions. Other engines differ too: some require lookbehind to have a fixed length, and some do not support it at all. Check your target engine's documentation before relying on it.

JavaScript· Run in Node: lookahead, lookbehind and a combined password check
console.log("price 50% off, 20 items".match(/\d+(?=%)/)[0]);  // 50
console.log("cost $45 and 30".match(/(?<=\$)\d+/)[0]);       // 45

const strong = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}$/;
console.log(strong.test("Passw0rdOK"));   // true
console.log(strong.test("password"));     // false

Flags and escaping user input

Flags follow the closing slash and change how the whole pattern behaves. The g flag finds every match instead of the first, i ignores case, m makes ^ and $ match at each line, s lets the dot match line breaks, u turns on full Unicode handling, and y sticks the match to the current position. Without the u flag, JavaScript treats an emoji as two units, and \w matches only ASCII letters, so accented characters are not word characters.

A regex with the g flag stores a lastIndex and carries it between calls to test and exec, which makes a reused regex object return alternating results. Create the regex inside the function, or reset lastIndex, when you test several strings. When you build a pattern from user input, escape it first, otherwise a search for a.b also matches axb and a stray parenthesis throws an error.

JavaScript· Run in Node: flag pitfalls and an escape helper
const re = /o/g;
console.log(re.test("foo"), re.lastIndex);   // true 2
console.log(re.test("foo"), re.lastIndex);   // true 3
console.log(re.test("foo"), re.lastIndex);   // false 0

console.log("Line1\nLine2".match(/^Line\d$/gm));   // [ 'Line1', 'Line2' ]
console.log("AbC".match(/abc/i)[0]);               // AbC
console.log(/^.$/.test("😀"), /^.$/u.test("😀"));   // false true

const esc = (s) => s.replace(/[.*+?^$\{}()|[\]\\]/g, "\\$&");
console.log(esc("1+1=2? (yes)"));                  // 1\+1=2\? \(yes\)
console.log(new RegExp(esc("a.b")).test("axb"));   // false

Practical patterns and what they cannot do

Every pattern here is a first filter, not a proof. The email pattern accepts anything shaped like text, an at sign, text, a dot, text. It rejects obvious typos but cannot tell whether the mailbox exists, and full email syntax is far too complicated for one reasonable regex. The reliable check is to send a confirmation message. The URL pattern checks for an http or https prefix and no spaces; use the URL constructor when you need to parse or truly validate. The date pattern checks the shape and ranges of month and day, yet it still accepts 2026-02-30, so parse it as a date afterwards.

For an Indian mobile number, the common generic format is ten digits starting with 6, 7, 8 or 9, optionally prefixed by +91 or a leading 0. The pattern checks only that shape. It does not know whether a number is active, and formats may change, so confirm with a one-time code if the number matters. A slug is lowercase letters and digits in groups separated by single hyphens.

JavaScript· Run in Node: six patterns with their results
const email = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const url   = /^https?:\/\/[^\s/$.?#][^\s]*$/i;
const date  = /^(\d{4})-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$/;
const mobile = /^(?:\+91[\s-]?|0)?[6-9]\d{9}$/;
const slug  = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;

console.log(["a@b.co", "a@b", "a b@c.com", "x@y.z.in"].map((s) => email.test(s)));
// [ true, false, false, true ]
console.log(["https://example.com/a?b=1", "http://x", "ftp://a.b", "https://"].map((s) => url.test(s)));
// [ true, true, false, false ]
console.log(["2026-11-26", "2026-13-01", "2026-02-30", "2026-1-1"].map((s) => date.test(s)));
// [ true, false, true, false ]   <- note 2026-02-30 passes
console.log(["9876543210", "+91 9876543210", "09876543210", "5876543210", "98765432"].map((s) => mobile.test(s)));
// [ true, true, true, false, false ]
console.log(["hello-world", "Hello", "a--b", "-a", "a1-b2"].map((s) => slug.test(s)));
// [ true, false, false, false, true ]
console.log("Hello, World! Ready?".toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, ""));
// hello-world-ready

Catastrophic backtracking and testing

JavaScript's regex engine tries alternatives by backtracking: when a match fails, it returns to an earlier choice and tries another. A pattern with nested quantifiers over the same characters, such as (a+)+$, can have an exponential number of ways to split a failing input, so a short string can freeze the thread for seconds. This is called catastrophic backtracking, and with user-supplied input it is a denial-of-service risk, known as ReDoS. The warning signs are nested quantifiers, or alternations whose branches overlap, inside a repeated group.

JavaScript· Run in Node: a slow pattern next to a safe one (timings vary by machine)
const input = "a".repeat(24) + "!";

let t = Date.now();
/^(a+)+$/.test(input);                       // nested quantifier: slow
console.log("nested ms:", Date.now() - t);

t = Date.now();
/^a+$/.test(input);                          // same meaning, no nesting: instant
console.log("flat ms:", Date.now() - t);

To avoid it, remove the nesting, prefer negated classes to .*, cap input length before matching, and never run a user-supplied pattern against large text. For testing, build a table of strings that must match and strings that must not, run them in a few lines of Node as above, and add every bug you meet as a new row. Interactive testers are helpful for exploring, but the final check belongs in your own code, using the engine you ship.

Practical tip: write the pattern in small steps and print the result after each one. Start with the literal part, add one quantifier or group, rerun, and keep the failing examples from every step in your test table.

Need this built properly for your business?

CodingMarble is a remote studio in India that builds websites, apps and games on fixed packages with the scope written down before payment. Try the free tools we run, or start a project when you are ready.