Skip to main content

Developer

Seven Regex Mistakes That Break JavaScript Code

Unescaped dots, missing anchors, greedy matches, the stateful g flag, and catastrophic backtracking - what each mistake looks like and how to test for it before it ships.

By 10 min read

Article

Regular expressions fail in a particular way: they usually work on the example you had in mind and break on the input you did not imagine. A pattern that validates every test case can still accept garbage, reject valid data, or freeze a server for seconds on one unlucky string.

These are the mistakes we see most often in JavaScript code, each with the symptom it produces and a concrete way to test for it. Every example uses the JavaScript RegExp engine, which is what browsers and Node.js run.

Who this is for

Developers who write validation rules, log parsers, or search-and-replace scripts, and reviewers who need to judge whether a pattern in a pull request is safe. Basic familiarity with character classes and quantifiers is assumed.

1. Forgetting that a dot matches almost anything

In a pattern, . means "any character except a line break". A version check written as /1.2.3/ matches 1.2.3, but also 1x2y3 and 10203. The same mistake appears in domain checks: /example.com/ matches examplexcom and, worse, example.com.attacker.net.

Escape literal dots as \. and test with a string where the dot is replaced by another character. If it still matches, the dot is unescaped.

2. Leaving out anchors

Without ^ and $, a pattern matches if it appears anywhere in the string. /\d{5}/ is meant to validate a five-digit postal code, but it happily accepts "abc123456789" because five digits appear somewhere inside. For validation, almost every pattern should be anchored: /^\d{5}$/.

The multiline flag m changes this. With m, ^ and $ match at the start and end of every line, so a multi-line input can pass validation if any one of its lines matches. Do not use m on validation patterns unless you mean it.

3. Greedy quantifiers that swallow too much

Quantifiers such as * and + are greedy: they match as much as possible and only give back characters when the rest of the pattern fails. Extracting a tag with /<.+>/ from "<b>bold</b>" returns the entire string, not "<b>", because .+ runs to the final >.

Two fixes exist. A lazy quantifier, /<.+?>/, stops at the first possible >. A negated character class, /<[^>]+>/, says exactly what is allowed and is usually faster and clearer. Prefer the negated class when you can name the stopping character.

4. Reusing a regex with the g flag

A RegExp object with the g or y flag is stateful. After a successful test() or exec(), its lastIndex property moves to the end of the match, and the next call starts searching from there. Calling the same /x/g.test() twice on the string "x" returns true and then false.

This bites hardest when a global regex is stored in a module-level constant and used to validate each item in a list: alternate items fail for no visible reason. Do not use g for yes-or-no checks, create the regex inside the function, or reset lastIndex to 0 before each use. String.prototype.matchAll and replaceAll are not affected in the same way because they work on an internal copy.

5. Catastrophic backtracking

Some patterns take exponential time on inputs that almost match. The textbook case is a nested quantifier such as /^(a+)+$/. On "aaaaaaaaaaaaaaaaaaaaaaaaaaaa!" the engine tries every possible way of splitting the run of a characters between the inner and outer group before concluding there is no match. Each extra character roughly doubles the work, so thirty characters can take seconds.

In a browser that freezes one tab. On a server, one request can block the event loop for every user, which is why this class of bug is called ReDoS, regular expression denial of service. Warning signs are nested quantifiers like (x+)+ or (x*)*, and alternations whose branches can match the same text, like (a|a)+ or (\w|\d)+.

To test, feed the pattern a long string of the repeated character followed by one character that makes the match fail, then lengthen it. If the time grows sharply with each extra character, rewrite the pattern so each character can be matched in only one way.

6. Escaping that changes inside a string

A regex literal and a regex built from a string need different escaping. /\d+/ works as written, but new RegExp("\d+") does not: in a JavaScript string, \d is just d, so the pattern becomes d+. The string must double the backslash.

Building a pattern from user input has the opposite risk. If someone searches for "1+1", passing that text straight to new RegExp makes + a quantifier. Escape special characters before inserting text into a pattern, or use plain string methods like includes() when you do not need regex features at all.

7. Expecting another language’s syntax to work

Patterns copied from Python, PCRE, or .NET answers often contain features JavaScript does not have, such as possessive quantifiers (a++), atomic groups, inline flag modifiers like (?i) in the middle of a pattern, or \A and \Z anchors. Some cause a syntax error; others are silently read as something else.

Modern JavaScript does support named groups written (?<year>\d{4}), lookbehind (?<=\$)\d+, the s flag that lets . match line breaks, and the u flag for full Unicode handling. If a pattern touches emoji or non-Latin scripts, add u; without it, characters outside the Basic Multilingual Plane count as two units and quantifiers split them.

How to test a pattern properly

A pattern is only as good as the strings you tried it on. Keep a small table of cases next to every non-trivial regex, and check both directions.

  • Strings that must match, including the shortest and longest valid values.
  • Strings that must not match, including a valid value with extra text before and after.
  • Edge cases: empty string, only whitespace, a trailing newline, and non-ASCII characters.
  • One long, almost-matching string to check for backtracking.
  • The same input twice in a row if the regex has the g or y flag.

When not to use a regex

Regex is the wrong tool for nested or recursive structures such as HTML, JSON, or balanced parentheses; use a parser. It is also a poor fit for full email or URL validation. The URL constructor parses URLs correctly, and for email a simple shape check followed by a confirmation message is more reliable than a pattern that tries to encode the whole specification.

Takeaway

Escape literal dots, anchor validation patterns, prefer negated classes over greedy wildcards, keep g out of yes-or-no checks, and watch for nested quantifiers. Then test against strings designed to break the pattern, not just the ones that prove it works. ToolMint’s Regex Tester runs the same JavaScript engine as your code, in your browser, so you can paste real log lines and payloads while you do it.