JavaScript logoJavaScript INTERMEDIATE

JavaScript Regular Expressions

Complete guide to regular expressions in JavaScript with patterns, methods, and practical examples

10 min read
regexregexppatternsvalidationjavascripttext-processing

Basic Patterns

Essential regex patterns and metacharacters

Character Classes

Matching specific sets of characters

📄 Codejavascript
💡 Dot (.) matches any character except newline - use [\s\S] for all
⚡ Character classes can be negated with ^ inside brackets
📌 \w includes underscore (_) in word characters
🟢 Combine classes: [a-zA-Z0-9] for alphanumeric
character-classesbasics

Anchors

Matching positions in text

📄 Codejavascript
💡 Use ^ and $ together for exact full string match
⚡ Word boundary \b is zero-width - doesn't consume characters
📌 Multi-line flag (m) changes ^ and $ behavior
🟢 \b is useful for matching whole words only
anchorsboundaries

Quantifiers

Specifying repetition

📄 Codejavascript
💡 Greedy quantifiers match as much as possible
⚡ Add ? after quantifier for lazy (minimal) matching
📌 {n,m} is inclusive - matches n to m times
🟢 Use ? for optional parts like https? for http/https
quantifiersrepetition

Groups & References

Capturing, non-capturing groups, and backreferences

Groups

Grouping patterns and capturing matches

📄 Codejavascript
💡 Use (?:) when you need grouping but not capturing
⚡ Named groups make code more readable and maintainable
📌 Backreferences match the exact same text, not pattern
🟢 Groups are numbered from left to right by opening paren
groupscapturing

Lookarounds

Assertions that don't consume characters

📄 Codejavascript
💡 Lookarounds are zero-width assertions - don't capture text
⚡ Use multiple lookaheads for complex validation rules
📌 Lookbehind has limited browser support in older versions
🟢 Great for matching based on context without including it
lookaroundassertions

Flags

Regex flags that modify pattern behavior

Pattern Flags

Modifiers that change how patterns work

📄 Codejavascript
💡 Global flag needed for methods like replaceAll and matchAll
⚡ Unicode flag enables \p{} for Unicode properties
📌 Sticky flag matches only at lastIndex position
🟢 Combine flags as needed: /pattern/gim
flagsmodifiers

String Methods

JavaScript methods that work with regex

Testing & Matching

Methods for pattern matching

📄 Codejavascript
💡 Use test() when you only need true/false
⚡ matchAll() requires global flag and returns iterator
📌 exec() with g flag remembers position via lastIndex
🟢 match() without g returns groups, with g returns all matches
methodstestingmatching

Replacing

Using regex with replace methods

📄 Codejavascript
💡 Use function replacer for complex transformations
⚡ $& inserts the entire match in replacement
📌 replaceAll() requires global flag or throws error
🟢 Named groups with $<name> improve readability
replacesubstitution

Splitting

Using regex to split strings

📄 Codejavascript
💡 Capture groups in split() include separators in result
⚡ Use lookahead/behind to split without losing delimiters
📌 filter(Boolean) removes empty strings from result
🟢 Useful for parsing CSV, commands, or structured text
splitparsing

Common Patterns

Frequently used regex patterns

Validation Patterns

Common validation regular expressions

📄 Codejavascript
💡 Email validation should be simple - use service for strict validation
⚡ Use lookaheads for password requirements
📌 Always validate on server side too
🟢 Test patterns with edge cases before using
validationpatterns

Text Processing

Patterns for text manipulation

📄 Codejavascript
💡 Use non-greedy quantifiers for nested patterns
⚡ Remember to escape special characters when needed
📌 Test with edge cases like empty strings
🟢 Chain replace calls for multiple transformations
textprocessing

Data Extraction

Extracting structured data from text

📄 Codejavascript
💡 Use matchAll() with named groups for structured extraction
⚡ Consider using dedicated parsers for complex formats
📌 Always handle null/undefined from match results
🟢 Named groups make extracted data self-documenting
extractionparsing

Advanced Techniques

Advanced regex patterns and optimization

Performance & Optimization

Writing efficient regular expressions

📄 Codejavascript
💡 Catastrophic backtracking can freeze your app
⚡ Compile regex once when using repeatedly
📌 Be as specific as possible with patterns
🟢 Sometimes a simple string method is faster than regex
performanceoptimization

Dynamic Patterns

Building regex dynamically

📄 Codejavascript
💡 Always escape user input to prevent regex injection
⚡ Use template literals for complex pattern building
📌 Remember to double-escape in string literals
🟢 Build reusable pattern factories for common needs
dynamicbuilding

Unicode & Internationalization

Working with Unicode and international text

📄 Codejavascript
💡 Always use u flag when working with Unicode
⚡ \p{} properties require Unicode flag
📌 normalize() helps with Unicode comparison
🟢 Test with actual international text samples
unicodeinternational

Debugging & Tools

Tips for debugging and testing regex

Debugging Techniques

Methods for testing and debugging patterns

📄 Codejavascript
💡 Break complex patterns into smaller testable parts
⚡ Use online tools like regex101.com for visual debugging
📌 Test edge cases: empty strings, special characters
🟢 Create test suites for important patterns
debuggingtesting