Online Compiler logoOnline Compiler

JavaScript Regular Expressions (Regex) Overview

Regular expressions (regex) are a compact, expressive way to describe patterns in text. In JavaScript, regex is used for searching, validating, replacing, and extracting strings without writing large amounts of manual parsing code. Good regex skills let you handle everything from simple validations to complex data extraction. This page walks through key concepts, practical examples, and common gotchas so you can write regex confidently.

What is a Regular Expression?

A regular expression is a sequence of symbols that defines a search pattern. Instead of checking each character manually, a regex engine reads the pattern and determines whether a string matches. Patterns can match exact text (e.g., hello), character sets (e.g., [a-z]), or even nested structures using groups. Regex is widely supported across languages, and in JavaScript it is built into the language via theRegExp object and literal syntax.

While regex is powerful, it can also be hard to read if overused. Learning how to structure patterns clearly, comment complex expressions (by splitting them into named parts), and validate their behavior with test cases will save you time and avoid bugs.

Regex Syntax Quick Tour

Regex syntax combines literal characters with special meta-characters. For example, \d matches digits,\w matches word characters, and quantifiers like + or * define how many times a match can repeat. You can group patterns using parentheses to capture parts of the match for later reuse.

Flags modify how a pattern is applied. Common flags include g (global), i (ignore case), and m (multiline). Understanding how flags affect match behavior is critical — especially when you use the same regex multiple times, because some flags change internal state.

Regex in JavaScript: Literals vs RegExp

JavaScript supports two ways to create regex patterns. The difference matters when patterns are static versus when they are built at runtime (for example, from user input).

  • Regex literal (e.g., /pattern/i) — evaluated once at parse time and is easy to read.
  • RegExp constructor (e.g., new RegExp('pattern', 'gi')) — useful when the pattern is generated dynamically or comes from external input.

When using the constructor, escape backslashes properly (e.g., new RegExp('\\d+')). Literal syntax is usually preferred for static patterns because it is shorter and easier to maintain.

Common Real-World Uses

Regex is especially useful in user input validation and text transformation. Instead of writing complex conditional logic to check whether an email address is valid or to parse a log entry, a well-crafted regex can do the job with a single expression. That said, keep patterns maintainable: comment complicated parts, break patterns into smaller pieces if needed, and prefer readability when possible.

Some common tasks where regex shines:

  • Validating form input like email addresses, phone numbers, and postal codes
  • Extracting structured information from raw text (logs, CSV, HTML snippets)
  • Replacing or sanitizing text (e.g., masking sensitive data)
  • Parsing custom mini-languages (e.g., markup, command syntax)

Try These Examples

The best way to learn regex is by experimenting with real patterns and seeing what they match. Use the examples below as a starting point, and adjust them in the online regex tester to see how they behave.

Match digits in a string

const pattern = /\d+/g;
const text = 'Order 123, Order 456';
console.log(text.match(pattern)); // ['123', '456']

The \`g\` flag makes the regex return all matches. Without it, the regex matches only the first number.

Validate a simple email address

const emailRegex = /^[w.-]+@[w-]+.[a-z]{2,}$/i;
console.log(emailRegex.test('user@example.com')); // true
console.log(emailRegex.test('user@invalid')); // false

This regex checks for a local part, an @ symbol, a domain, and a top-level domain. Real-world email validation often requires more rules, but this is a strong baseline.

Use capture groups to reformat text

const input = '2026-03-13';
const output = input.replace(/(\d{4})-(\d{2})-(\d{2})/, '$1/$2/$3');
console.log(output); // '2026/03/13'

Capture groups (parentheses) let you reuse pieces of the matched text in the replacement. The placeholders $1, $2, etc., refer to each group.

Debugging and Best Practices

Regex can become hard to read, especially when using many special characters. When your patterns grow beyond a few dozen characters, consider using a regex builder tool or adding comments. Some developers split patterns into smaller named pieces using string concatenation (when using the RegExp constructor), which lets you document the intent for each part.

Also be mindful of performance. Complex patterns with nested quantifiers can cause catastrophic backtracking, which slows execution dramatically for certain inputs. If you notice a regex running slowly, try simplifying the pattern or using a different approach (like parsing with string methods or a parser library).

Where to Next?

Once you're comfortable with the basics, explore the dedicated pages on this site for more depth:

  • Regex Patterns & Flags — dive deeper into character classes, quantifiers, and lookarounds.
  • Regex Methods — learn about match, replace, test, and how different methods behave with global patterns.
  • Regex Tester — use the interactive tool to debug patterns and visualize matches.