Everything, Everywhere
Verified Specification | Standardized Formulas | Instant Precision
Secure & Private (Zero Data Retention) Free Access • No Sign-Up

Regular Expressions

Regular expressions are patterns used to match character combinations in strings.

Try It Yourself

      
📋 Copy JavaScript Regex Named Capture Groups Snippet
// Named Capture Groups & Testing
const logPattern = /\[(?<level>INFO|WARN|ERROR)\]\s+(?<msg>.*)/u;
const match = logPattern.exec("[ERROR] Connection refused to database");

if (match) {
  const { level, msg } = match.groups;
  console.log(`Level: ${level} | Message: ${msg}`);
}

⚠️ 5 Fatal Traps & JavaScript Pitfalls

Trap #1: Global Flag (/g) Stateful lastIndex Bug
When using the /g flag, RegExp objects store internal state on lastIndex. Calling regex.test(str) repeatedly alternates between returning true and false! Reset regex.lastIndex = 0.
Trap #2: Catastrophic Backtracking (ReDoS Vulnerability)
Nested quantifiers like (a+)+$ cause exponential backtracking on non-matching inputs, freezing the CPU for minutes (Regular Expression Denial of Service).
Trap #3: Unescaped User Input in Dynamic new RegExp()
Passing unsanitized strings to new RegExp(input) crashes if the user types regex special characters like [ or ?. Escape special characters first.
Trap #4: Greedy vs. Lazy Quantifier Confusion
By default, quantifiers like .* are greedy and match as much text as possible. Append ? (e.g. .*?) for lazy minimal matching.
Trap #5: Omitting the Unicode (/u) Flag
Without the u flag, regular expressions treat emojis as surrogate pairs of separate characters, breaking matching on non-ASCII symbols.

💬 Frequently Asked Questions

What do named capture groups (?...) provide in JavaScript regex?
Named capture groups allow extracted substrings to be accessed via match.groups.name instead of fragile numeric array indexes.
What is the difference between RegExp.prototype.test() and RegExp.prototype.exec()?
test() returns a boolean indicating whether a match exists. exec() returns a detailed result array with captured groups, indexes, and full match strings.
What does the /s (dotAll) flag do in regular expressions?
The s flag allows the dot . metacharacter to match newline characters (\n, \r), which it skips by default.
What are positive and negative lookaheads?
Positive lookahead (?=pattern) asserts that what follows matches pattern without including it in the match. Negative lookahead (?!pattern) asserts that what follows does NOT match.
How do you safely escape user input before creating a RegExp?
Replace all special characters: string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&").
Sponsored Utility
While You're Here
Sponsored Recommendations
Advertisement