</> DevDrillsSupport

JavaScript Drill

Common regex mistakes in JavaScript.

Regular expressions are powerful, but small mistakes can completely change matching behavior. Understanding common regex problems helps you debug patterns faster and write safer matching logic.

6 min read

Forgetting to escape special characters

Some characters have special meaning in regular expressions. For example:

. * + ? ^ $ { } ( ) | [ ] \

If you want to match a literal dot instead of “any character”, you must escape it:

// wrong
/./

// correct
/\./

Forgetting the global flag

Without the g flag, JavaScript usually returns only the first match.

const text = "React Redux React";

// only first match
text.match(/React/);

// all matches
text.match(/React/g);

This is one of the most common regex mistakes when working with lists, logs, or repeated text.

Greedy matching

Quantifiers like * and + are greedy by default. They try to match as much text as possible.

const text = "<div>Hello</div><div>World</div>";

// greedy
/<div>.*<\/div>/

// lazy
/<div>.*?<\/div>/

Lazy matching uses ? to stop matching earlier.

Matching too much text

Broad patterns can accidentally match data you never intended to capture.

// too broad
/.+@.+/

// safer
/[a-zA-Z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}/

Specific patterns are usually safer and easier to debug.

Not understanding multiline mode

The m flag changes how ^ and $ behave.

const text = "first line
second line";

// without m
/^second/

// with m
/^second/m

Multiline mode allows regex anchors to work per line instead of only at the beginning or end of the entire string.

Regex can become unreadable

Complex regular expressions are difficult to maintain if everything is packed into one line.

Bad approach

One giant unreadable regex nobody understands later.

Better approach

Smaller patterns, comments, validation steps, and clear naming.

Sometimes normal JavaScript string methods are easier and safer than a complicated regex.

Common regex flags

g

Global search. Finds all matches instead of only the first.

i

Case-insensitive matching.

m

Multiline mode for ^ and $ anchors.

Try the tool

Test regex patterns instantly

Use the DevDrills Regex Tester to experiment with JavaScript regular expressions, inspect matches, and test regex flags directly in your browser.

Open Regex Tester