Regex Cheat Sheet: Practical JavaScript Examples
Learn regex anchors, character classes, groups, and flags with copyable JavaScript examples, matching test cases, and common mistakes to avoid.
The regex syntax you will use most often
A regex describes a text pattern. Character classes choose which characters may appear, quantifiers control repetition, and anchors constrain where the match starts or ends. Add one constraint at a time so failed matches are easier to explain.
| Pattern | Meaning | Example |
|---|---|---|
| [0-9] | One ASCII digit | 7 |
| [A-Za-z] | One ASCII letter | Q |
| [^0-9] | One character that is not an ASCII digit | x |
| {2,4} | Repeat the previous item two to four times | [0-9]{2,4} |
| + | One or more repetitions | [A-Z]+ |
| ? | Zero or one repetition | colou?r |
| ^ and $ | Start and end boundaries; behavior depends on flags | ^[0-9]+$ |
| (a|b) | Group with alternatives | (cat|dog) |
Copyable patterns and expected results
For the site’s tester, enter only the pattern in the pattern field and set flags separately. JavaScript source code uses slashes to delimit a regex literal; those slashes are not part of the pattern you paste into that field.
The ZIP pattern below checks US ZIP code shape only. It does not establish that a postal code exists or that an address is deliverable. Other countries use different formats, so select validation rules based on the address country.
const zip = /^[0-9]{5}(?:-[0-9]{4})?$/;
console.log(zip.test("02108")); // true
console.log(zip.test("02108-1234")); // true
console.log(zip.test("2108")); // false
const hexColor = /^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i;
console.log(hexColor.test("#0d9488")); // true
console.log(hexColor.test("#xyz")); // false
const slug = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
console.log(slug.test("json-format-101")); // true
console.log(slug.test("-json")); // falseChoose flags deliberately
The i flag enables case-insensitive matching. The g flag finds multiple matches. The m flag lets anchors match line boundaries within a multiline string, and s lets a dot match line terminators. The u flag enables Unicode-aware parsing and features such as Unicode property escapes.
Repeated test calls on a regex with g or y update lastIndex, which can make validation appear inconsistent. For a simple yes-or-no form validation check, avoid those stateful flags unless you explicitly manage lastIndex.
const numbers = "Order 42, batch 17".match(/[0-9]+/g);
console.log(numbers); // ["42", "17"]
const letters = /^\p{L}+$/u;
console.log(letters.test("Montréal")); // true
console.log(letters.test("Paris7")); // falseEscape a backslash in JavaScript strings
A regex literal and a string passed to RegExp are parsed differently. In a string, the JavaScript parser consumes escapes before the regular expression parser sees the value. Double the backslash to preserve a regex escape.
For a literal dot, use an escaped dot in the pattern. An unescaped dot generally matches any character except line terminators, so a pattern intended for a filename can accidentally accept unrelated text.
const literal = /\d+/;
const fromString = new RegExp("\\d+");
console.log(literal.test("item42")); // true
console.log(fromString.test("item42")); // trueKnow when regex is the wrong validator
Use a JSON parser for JSON and a URL parser for URLs. An email regex can check a rough shape, but mailbox verification requires a confirmation flow. International names can include spaces, apostrophes, combining marks, and characters outside Latin alphabets; a short ASCII-only pattern is not a universal name validator.
Test empty strings, leading or trailing whitespace, long input, and near-misses. Nested repetition such as (a+)+ can require excessive work on failing input. Keep patterns bounded where practical and avoid testing potentially expensive patterns against large text in a browser tab.
A passing match proves only the condition encoded by that pattern. Keep domain checks separate: a correctly shaped date can still be impossible, and a syntactically valid identifier can still be absent from your database.
Frequently asked questions
Why does a regex work in one language but fail in another?
Regex engines differ in supported syntax, escaping rules, flags, and Unicode behavior. These examples target JavaScript; check your runtime before reusing them in Python, Java, SQL, or a command-line tool.
Should I use regex to validate an email address?
Use a modest format check to help users catch obvious mistakes, then verify ownership by sending a confirmation message. A regex cannot prove an address exists or can receive mail.
References
Check the official documentation for command options and runtime-specific behavior.
Integrated Tools & Learning Resources
DevX Tool combines deep engineering tutorials with client-side interactive tooling so you can test code, verify outputs, and troubleshoot bugs right away.
Related tutorials and articles
Fix LangChain OutputParserException and Truncated Output
Debugging "OutputParserException: Failed to parse" and Regex Truncation in LangChain and LlamaIndex
Read article Performance & AlgorithmsHow to Prevent Regex Backtracking and ReDoS
Preventing Catastrophic Backtracking and Regular Expression Denial of Service (ReDoS) in High-Load APIs
Read article Performance & AlgorithmsRegex Lookahead and Lookbehind Explained
Mastering Lookaround Assertions: Positive/Negative Lookaheads and Lookbehinds with Zero-Width Matches
Read article Web troubleshootingHTTP Error Codes: 400, 401, 403, 404, 429 & 500
Find what common HTTP errors mean, what to check in an API response, and when a retry can help. Includes a status-code comparison and debugging steps.
Read article