DevX Tool
Back to Tech Blog
Web Development 4 min read DevX Tool Team

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.

Regex JavaScript Validation

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.

The regex syntax you will use most often
PatternMeaningExample
[0-9]One ASCII digit7
[A-Za-z]One ASCII letterQ
[^0-9]One character that is not an ASCII digitx
{2,4}Repeat the previous item two to four times[0-9]{2,4}
+One or more repetitions[A-Z]+
?Zero or one repetitioncolou?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.

JavaScript
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"));           // false

Choose 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.

JavaScript
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"));   // false

Escape 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.

JavaScript
const literal = /\d+/;
const fromString = new RegExp("\\d+");
console.log(literal.test("item42"));    // true
console.log(fromString.test("item42")); // true

Know 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.

Advertisement
Put Knowledge Into Practice

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