JavaScript Cheatsheet
Regular Expressions
Use this JavaScript reference while you build software engineering projects, review code for technical interview prep, or polish examples for a software engineer resume.
Creating Regular Expressions
// Literal syntax — preferred for static patterns const re = /hello/i; const digits = /\d+/g; // Constructor — required for dynamic patterns const pattern = "hello"; const re2 = new RegExp(pattern, "i"); const re3 = new RegExp(`\\d{${min},${max}}`); // escape backslashes // Test /abc/.test("abcdef") // true /xyz/.test("abcdef") // false
Flags
| Flag | Name | Description |
|---|---|---|
g | global | Find all matches (not just first) |
i | ignoreCase | Case-insensitive |
m | multiline | ^/$ match line start/end (not just string) |
s | dotAll | . matches \n too (ES2018) |
u | unicode | Full Unicode support; enables \u{HHHH} |
v | unicodeSets | Extended unicode sets (ES2024) |
y | sticky | Match only at lastIndex |
d | hasIndices | Add indices to match result (ES2022) |
/hello/gi // global + case-insensitive /^start/m // multiline /.+/s // dotAll — "." matches newlines too /\p{L}+/u // Unicode letter (requires u flag)
Character Classes
// Predefined classes \d // digit: [0-9] \D // non-digit \w // word char: [a-zA-Z0-9_] \W // non-word char \s // whitespace: space, tab, newline, etc. \S // non-whitespace . // any char except \n (use /s flag to include \n) // Custom character classes [abc] // a, b, or c [a-z] // lowercase a to z [A-Za-z0-9] // alphanumeric [^abc] // NOT a, b, or c (negated) [a-z&&[^aeiou]] // intersection (v flag) // Unicode classes (u flag required) \p{Letter} // any Unicode letter \p{Digit} // any Unicode digit \p{Emoji} // emoji \P{Letter} // negated: non-letter // Escape special chars \. \\ \^ \$ \* \+ \? \{ \} \[ \] \( \) \|
Anchors
^ // start of string (or line with /m) $ // end of string (or line with /m) \b // word boundary (between \w and \W) \B // NOT a word boundary \A // not in JS — use ^ \Z // not in JS — use $ /^\d+$/.test("123") // true — entire string is digits /\bword\b/.test("a word here") // true /\bword\b/.test("swordfish") // false
Quantifiers
// Greedy (match as much as possible) a* // 0 or more a+ // 1 or more a? // 0 or 1 a{3} // exactly 3 a{3,} // 3 or more a{3,5} // 3 to 5 // Lazy (match as little as possible) — add ? a*? // 0 or more, lazy a+? // 1 or more, lazy a{3,5}? // 3 to 5, lazy // Example: greedy vs lazy "<b>bold</b>".match(/<.+>/) // ["<b>bold</b>"] greedy "<b>bold</b>".match(/<.+?>/) // ["<b>"] lazy
Groups and Alternation
// Capturing group — captures matched text /(ab)+/.exec("ababab")[1] // "ab" (last capture) // Named capturing group (ES2018) /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/ // Non-capturing group — group without capturing (?:abc)+ // Alternation /cat|dog/.test("I have a cat") // true /(red|blue) car/ // Backreference to group /(\w)\1/.test("aa") // true — repeating char /(?<w>\w)\k<w>/.test("aa") // named backreference // Lookahead / Lookbehind (zero-width assertions) /foo(?=bar)/ // positive lookahead — "foo" only if followed by "bar" /foo(?!bar)/ // negative lookahead — "foo" only if NOT followed by "bar" /(?<=foo)bar/ // positive lookbehind — "bar" only if preceded by "foo" /(?<!foo)bar/ // negative lookbehind — "bar" only if NOT preceded by "foo" "foobar".match(/foo(?=bar)/) // ["foo"] "foobar".match(/(?<=foo)bar/) // ["bar"]
String Methods with Regex
const str = "Hello World 123"; // test — boolean /\d+/.test(str) // true // match — returns array or null str.match(/\d+/) // ["123", index:12, input:"Hello World 123"] str.match(/\w+/g) // ["Hello","World","123"] (global — no groups) str.match(/(\w)\w*/g) // ["Hello","World","123"] (global ignores groups) // matchAll — iterator of all matches with groups (requires /g) const re = /(\w+)\s(\w+)/g; for (const match of str.matchAll(re)) { console.log(match[0], match[1], match[2]); // match.index, match.input available too } [...str.matchAll(/\d+/g)] // all matches as array // search — index of first match, -1 if none str.search(/\d/) // 12 // replace str.replace(/\d+/, "NUM") // "Hello World NUM" (first only) str.replace(/\d+/g, "NUM") // all (with /g) "John Smith".replace(/(\w+) (\w+)/, "$2, $1") // "Smith, John" str.replace(/(\w+)/g, (match, p1) => p1.toUpperCase()) // "HELLO WORLD 123" // replaceAll — string or regex with /g str.replaceAll("l", "L") // "HeLLo WorLd 123" // split "a1b2c3".split(/\d/) // ["a","b","c",""] "one,two;three".split(/[,;]/) // ["one","two","three"]
exec — Iterating Matches
const re = /\d+/g; const str = "12 monkeys ate 45 bananas"; let match; while ((match = re.exec(str)) !== null) { console.log(`Found ${match[0]} at index ${match.index}`); // re.lastIndex advances automatically } // "Found 12 at index 0" // "Found 45 at index 15" // exec with named groups const dateRe = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/; const m = dateRe.exec("2024-06-15"); m.groups.year // "2024" m.groups.month // "06" m.groups.day // "15"
Common Patterns
// Email (basic) /^[^\s@]+@[^\s@]+\.[^\s@]+$/ // URL /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\.[a-zA-Z]{2,}/ // IPv4 /^(\d{1,3}\.){3}\d{1,3}$/ // Phone (US) /^\+?1?\s?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}$/ // Date YYYY-MM-DD /^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$/ // Hex color /^#([0-9a-f]{3}|[0-9a-f]{6})$/i // Slug (URL-safe string) /^[a-z0-9]+(?:-[a-z0-9]+)*$/ // Whitespace only /^\s*$/ // Strong password (min 8, upper, lower, digit, special) /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/ // Match balanced content (non-greedy) /<[^>]+>/g // HTML tags /\{[^}]*\}/g // curly brace content /"[^"]*"/g // double-quoted strings
Regex Object Properties
const re = /\w+/gi; re.flags // "gi" re.source // "\\w+" re.global // true re.ignoreCase // true re.multiline // false re.sticky // false re.unicode // false re.dotAll // false // lastIndex — relevant for /g and /y const gRe = /\d+/g; gRe.lastIndex // 0 (initial) gRe.exec("1 2 3") // matches "1", lastIndex = 1 gRe.exec("1 2 3") // matches "2", lastIndex = 3 // Reset for reuse gRe.lastIndex = 0;
Sticky Flag (y)
// /y matches only at lastIndex (no jumping ahead) const stickyRe = /\d+/y; stickyRe.lastIndex = 5; stickyRe.exec("hello 123") // ["123"] — matches at index 6? no, exactly 5 // If no match at lastIndex, returns null (won't search further)
Unicode Mode (u / v)
// u flag: proper Unicode support /\u{1F600}/u.test("😀") // true (code point escape) /./u.test("😀") // true (emoji is 1 char in unicode mode) /./test("😀") // true? (emoji is 2 UTF-16 units — may surprise) // Unicode property escapes (u or v required) /\p{Script=Latin}/u.test("hello") // true /\p{Emoji}/u.test("😀") // true /\p{Currency_Symbol}/u.test("$") // true // v flag (ES2024): enables set operations in character classes /[\p{Letter}--\p{ASCII}]/v // non-ASCII letters only (difference) /[\p{Letter}&&\p{Uppercase_Letter}]/v // intersection