Regular Expressions

Regular Expressions (RegEx) are patterns used to match character combinations in strings. In JavaScript, they provide a powerful way to search, replace, and validate text.

Illustration of Regular Expressions
Illustration of Regular Expressions

💡 What is a Regular Expression?

A sequence of characters that defines a search pattern, mainly for string pattern matching.

Creating Regular Expressions

Two ways to create a RegEx:

  • /pattern/flags — literal syntax
  • new RegExp("pattern", "flags") — constructor syntax
Common Flags
FlagMeaning
gGlobal search (all matches)
iCase-insensitive search
mMultiline search

Basic Patterns

  • .: Matches any single character except newline
  • \d: Matches any digit (0-9)
  • \w: Matches any word character (alphanumeric + underscore)
  • \s: Matches any whitespace (space, tab, newline)
  • ^: Matches start of string
  • $: Matches end of string

Quantifiers

  • *: 0 or more times
  • +: 1 or more times
  • ?: 0 or 1 time (optional)
  • {n}: Exactly n times
  • {n,}: At least n times
  • {n,m}: Between n and m times

Character Sets and Groups

  • [abc]: Matches any one character a, b, or c
  • [^abc]: Matches any character except a, b, or c
  • (abc): Capturing group - matches "abc"
  • (?:abc): Non-capturing group

💡 Using RegEx Methods

Common methods include:

  • test(str): Returns true if pattern matches
  • exec(str): Returns detailed match info or null
  • str.match(regexp): Returns matches in string
  • str.replace(regexp, replacement): Replaces matches
  • str.search(regexp): Returns index of first match or -1

📌 Deep Dive: Simple Validation with RegEx

JAVASCRIPT
const emailPattern = /^[\w.-]+@[a-zA-Z\d.-]+\.[a-zA-Z]{2,}$/;

console.log(emailPattern.test("user@example.com")); // true
console.log(emailPattern.test("invalid-email"));    // false
Output
true
false

⚠️ Important

Regular expressions can be complex and hard to read. Test thoroughly and comment patterns for clarity.

Tips for Beginners

  • Test your regular expressions using online tools like regex101.com
  • Start simple and build your pattern incrementally
  • Use parentheses for capturing parts you want to extract
  • Remember that RegEx is case-sensitive unless you use the i flag