JavaScript Regular Expressions

Beginner
⏱️ 18 min read
📚 Updated: Jul 2026
🎯 44 Tutorials
RegExp object

What You’ll Learn

Regular expressions power search, validation, and text cleanup across JavaScript apps. This hub links to 44 RegExp tutorials — from exec() and test() through character classes, quantifiers, anchors, and flags.

01

/pattern/

Literals

02

test()

Yes / no

03

exec()

Captures

04

\d + *

Patterns

05

g i m

Flags

06

44 guides

Full index

Introduction

A regular expression (regex) is a compact language for describing text patterns. In JavaScript, patterns live in RegExp objects. You use them to validate emails, extract numbers, strip HTML tags, or find every word in a paragraph.

What Are Regular Expressions?

Regex combines literal characters (match exactly) with special tokens like \d (digit), + (one or more), and [a-z] (character range). The engine scans a string left to right and reports whether — and where — the pattern matched.

💡
Beginner Tip

Start with simple literal patterns like /cat/, then add anchors (^, $) for whole-field validation. Complex patterns are built from small, testable pieces.

Two Ways to Create a RegExp

  • Literal/pattern/flags when the pattern is fixed in source code.
  • Constructornew RegExp("pattern", "flags") when the pattern comes from user input or variables.
  • String methodsstr.match(), str.replace(), and str.search() accept regex too.

Pattern Building Blocks

  • Character classes[0-9], [a-z], [^abc] (negated).
  • Metacharacters\d, \w, \s, . (wildcard).
  • Quantifiers?, +, *, {2,5} control repetition.
  • Groups(abc) capture parts; (a|b) alternation.
  • Flagsg global, i ignore case, m multiline.

📝 Syntax

Create a regex and test a string:

JavaScript
const email = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const ok = email.test("ada@example.com");

const digits = /\d+/g;
const found = "Order 42 and 7".match(digits); // ["42", "7"]

Common RegExp methods

MethodReturnsBest for
regex.test(str)true / falseValidation, guards
regex.exec(str)Match array or nullCapture groups, loops with g
str.match(regex)Matches array or nullQuick extraction
str.replace(regex, repl)New stringCleanup and substitution

⚡ Quick Reference

GoalPattern / API
Any digit\d or [0-9]
Word characters\w (letters, digits, _)
Start of string^
End of string$
One or more+
Optional?
Exact count{4} (e.g. PIN length)
Case insensitive/pattern/i

When to Use Regular Expressions

  • Form validation — emails, phone numbers, postal codes (combine with anchors).
  • Search & replace — normalize whitespace, strip tags, redact tokens.
  • Parsing logs — extract timestamps, IDs, and status codes from lines.
  • Tokenizing — split on delimiters with str.split(/[,;]+/).
  • When not to use regex — HTML/XML parsing, full email RFC compliance, or nested structures — reach for dedicated parsers instead.

👀 Sample Match Results

Same string, different regex goals:

/\bcat\b/i.test("The CAT sat") → true /\d+/.exec("Room 404") → ["404", index: 5, …] "hi@x.co".match(/^[^\s@]+@[^\s@]+$/) → ["hi@x.co"]

RegExp Tutorial Index

Search by method, token, or flag. Each tutorial includes syntax, five try-it examples, and FAQs.

Instance Methods

4 tutorials

Run matches, test strings, and inspect RegExp objects.

TopicDescriptionTutorial
exec()Run a match and return capture groups, index, and input — or null.Open
test()Return true or false when a pattern matches anywhere in a string.Open
compile()Legacy method to recompile an existing RegExp (prefer new RegExp).Open
toString()Return the /pattern/flags string representation of a RegExp.Open

Properties

3 tutorials

Read flags and constructor information on a RegExp instance.

TopicDescriptionTutorial
constructorPoints to the RegExp function that created the regex object.Open
globalTrue when the g flag is set — find all matches, not just the first.Open
ignoreCaseTrue when the i flag is set — case-insensitive matching.Open

Character Classes

5 tutorials

Match one character from a set, range, or negated group.

TopicDescriptionTutorial
[0-9]Character class matching any digit from 0 through 9.Open
[abc]Match any one character from the set inside the brackets.Open
[^0-9]Negated class — match any character that is not a digit.Open
[^abc]Negated class — match any character not in the set.Open
(x|y)Alternation — match either the left or right sub-pattern.Open

Metacharacters

18 tutorials

Shorthand tokens for digits, whitespace, word chars, and escapes.

TopicDescriptionTutorial
\bWord boundary between a word and non-word character.Open
\rCarriage return character.Open
\dShorthand for any digit — equivalent to [0-9].Open
.Wildcard — matches any character except newline (by default).Open
\fForm feed character.Open
\nLine feed (newline) character.Open
\DAny non-digit character.Open
\SAny non-whitespace character.Open
\WAny non-word character (not letter, digit, or _).Open
\BNot a word boundary — opposite of \b.Open
\0Null character (U+0000).Open
\sWhitespace — spaces, tabs, newlines, and similar.Open
\tHorizontal tab character.Open
\uXXXXUnicode code point by four hex digits.Open
\vVertical tab character.Open
\wWord character — letters, digits, and underscore.Open
\xHHByte value by two hex digits.Open
\oooByte value by one to three octal digits (legacy).Open

Modifiers (Flags)

4 tutorials

Change how the engine matches — global, case, multiline, indices.

TopicDescriptionTutorial
d (indices)HasIndices flag — exec results include match indices.Open
g (global)Global flag — continue searching after each match.Open
i (ignoreCase)Ignore case when matching letters.Open
m (multiline)Multiline flag — ^ and $ match line boundaries.Open

Anchors & Lookahead

4 tutorials

Pin matches to positions and peek ahead without consuming text.

TopicDescriptionTutorial
^Start anchor — match must begin at the start (or line with m).Open
$End anchor — match must end at the end (or line with m).Open
(?!…)Negative lookahead — succeed only if pattern ahead fails.Open
(?=…)Positive lookahead — require a pattern ahead without consuming it.Open

Quantifiers

6 tutorials

Control how many times a token repeats.

TopicDescriptionTutorial
+One or more repetitions of the preceding token.Open
?Zero or one repetition — makes the preceding token optional.Open
*Zero or more repetitions of the preceding token.Open
{X}Exactly X repetitions of the preceding token.Open
{X,}At least X repetitions (no upper limit).Open
{X,Y}Between X and Y repetitions inclusive.Open

Examples Gallery

Open DevTools Console (F12) and paste each snippet to see regex in action.

📚 Create & Test

Literals, flags, and boolean checks.

Example 1 — Regex Literal with the i Flag

Match a word regardless of letter case.

JavaScript
const greeting = "Hello World";
const regex = /hello/i;

console.log(regex.test(greeting)); // true
i flag Tutorial

How It Works

The i flag makes /hello/i match Hello, HELLO, and any case mix. Without i, the match would fail.

Example 2 — Validate with test()

Check whether a string contains only digits.

JavaScript
const pin = "482910";
const onlyDigits = /^\d+$/;

console.log(onlyDigits.test(pin));      // true
console.log(onlyDigits.test("48a2"));   // false
test() Tutorial

How It Works

^ and $ anchor the pattern to the whole string. \d+ means one or more digits. test() returns a simple boolean — ideal for validation.

📈 Extract & Replace

Pull data out of text and transform it.

Example 3 — Capture Groups with exec()

Extract the username and domain from an email-like string.

JavaScript
const line = "Contact: ada@example.com today";
const email = /(\w+)@([\w.]+)/;
const m = email.exec(line);

console.log(m[0]); // full match
console.log(m[1]); // ada
console.log(m[2]); // example.com
exec() Tutorial

How It Works

Parentheses create capture groups. Index 0 is the full match; 1 and 2 hold grouped parts. Use exec() when you need structured data, not just true/false.

Example 4 — Replace with a Global Regex

Swap every digit with a mask character.

JavaScript
const card = "4111-2222-3333-4444";
const masked = card.replace(/\d/g, "*");

console.log(masked);
g flag Tutorial

How It Works

Without g, replace changes only the first match. The global flag replaces every digit. Pair with \d from the metacharacter tutorials.

Example 5 — Simple Email Shape Check

A practical (not RFC-perfect) pattern for beginner forms.

JavaScript
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

console.log(emailPattern.test("user@mail.com"));  // true
console.log(emailPattern.test("not-an-email"));   // false
^ anchor Tutorial

How It Works

^ and $ require the entire input to match. [^\s@]+ means “one or more characters that are not whitespace or @.” Real apps may still verify via a confirmation email.

💬 Usage Tips

  • Anchor whole fields — use ^ and $ in validation so abc123 does not pass a digits-only rule.
  • Prefer literals for fixed patterns/\d+/ is clearer than new RegExp("\\d+").
  • Escape user input — when building new RegExp from variables, escape metacharacters first.
  • Reset lastIndex — global regexes remember position; set regex.lastIndex = 0 before reusing.
  • Search this index — jump to any of 44 tutorials above.

⚠️ Common Pitfalls

  • Greedy quantifiers.* may swallow too much; use non-greedy .*? when needed.
  • Missing anchors/\d+/ matches a substring; /^\d+$/ validates the whole value.
  • Global flag side effectstest() and exec() advance lastIndex on /g regexes.
  • Overly complex patterns — split into named steps or use a parser for nested data (JSON, HTML).
  • Octal escapes\123 can be ambiguous; prefer \xHH or \uXXXX.

🧠 How RegExp Matching Works

1

Compile pattern

JavaScript turns /pattern/flags into an internal RegExp object.

Parse
2

Scan input

The engine walks the string, trying the pattern at each position (unless anchored).

Search
3

Return result

test() yields boolean; exec() yields match data or null.

Report
=

Text superpowers

Validation, extraction, and cleanup become declarative one-liners instead of manual loops.

🖥 Browser & Node Support

RegExp and core methods (test, exec, string match/replace) are supported in every modern browser and all Node.js versions. Newer flags like d (indices) and u (Unicode) require recent engines — check MDN for your target.

Baseline · ES3+

RegExp.prototype methods

Production-safe across all current runtimes. Pattern syntax follows ECMAScript rules; test in your environment when using newer flags.

100% Core API

🎉 Conclusion

Regular expressions turn messy string work into focused patterns. Start with test() and exec(), learn \d and quantifiers, then explore flags and anchors as your validation needs grow.

Use the searchable index to open all 44 tutorials — each includes try-it labs and FAQs.

💡 Best Practices

✅ Do

  • Use ^ and $ for full-string checks
  • Test patterns on real sample inputs
  • Prefer \d, \w, \s shorthands
  • Comment complex patterns in code
  • Reset lastIndex on reused global regexes

❌ Don’t

  • Parse HTML with regex alone
  • Forget to escape user-supplied fragments
  • Reuse /g regexes without resetting state
  • Assume one regex validates RFC-perfect email
  • Memorize all 44 tokens at once

Key Takeaways

Knowledge Unlocked

Five things to remember about regex

Your gateway to 44 pattern tutorials.

5
Core concepts
? 02

test()

Boolean

Validate
() 03

Groups

Capture

exec()
+ 04

Quantifiers

Repeat

*, +, ?
44 05

Index

Search all

Ref

❓ Frequently Asked Questions

A RegExp is a pattern that describes text to find in strings. You create one with a literal like /hello/i or new RegExp('hello', 'i'), then use methods like test(), exec(), or String methods match, replace, and search.
Use test() when you only need true or false — form validation, guards, filters. Use exec() when you need the matched text, capture groups, or the index where the match started.
g (global) finds all matches instead of stopping at the first. i (ignoreCase) makes letters match regardless of case. m (multiline) makes ^ and $ match the start and end of each line, not just the whole string.
They match the same thing — any digit. \d is shorthand and easier to read. [0-9] is explicit and useful when you need custom ranges like [2-9].
By default, . matches any character except line terminators. Use the s (dotAll) flag in modern engines, or [\s\S] as a workaround, when you need . to span multiple lines.
Read the overview, try the five examples, then open exec() or test() under Instance Methods. Use the search box to jump to any of the 43 pattern and method tutorials.
Did you know?

JavaScript regex literals cannot be empty — // starts a line comment. To match a forward slash in a literal, escape it: /\//. With new RegExp, pass "\\/" instead.

Start with exec()

Learn how to run a pattern match and read capture groups from the result.

exec() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

10 people found this page helpful