Skip to content

Search

Articles, tools, solutions and knowledge base guides

Start typing to search across articles, tools and apps.

JavaScript Regular Expressions: How to Write Correct and Safe Patterns

An identifier validator accepts a substring, a regex test alternates between true and false, or a search misses accented letters. These are often pattern or API design problems rather than malformed data. This guide shows how to validate complete values, extract structured text and avoid expensive matching.

Published Written by Reading time 7 min read
On this page Contents: quick navigation between sections

How do you validate the entire value?

const orderIdPattern = /^ORD-[0-9]{6}$/;

function isOrderId(value) {
  return typeof value === "string" && orderIdPattern.test(value);
}

console.log(isOrderId("ORD-012345")); // true
console.log(isOrderId("prefix ORD-012345")); // false
console.log(isOrderId("ORD-012345\n")); // false
console.log(isOrderId(123456)); // false

An order identifier must contain ORD- followed by exactly six ASCII digits. [0-9] is a character class, {6} requires six occurrences, and ^ and $ constrain matching to input boundaries when m is absent. test() returns a boolean. [1][3]

Do not enable m for a whole-value validator: it changes the anchors to line boundaries. Regex literals and new RegExp() use the same pattern syntax, but a normal JavaScript string passed to the constructor needs doubled backslashes, as in new RegExp("\\d+"). [12]

Why does test() alternate between true and false?

const statefulPattern = /\d+/g;

console.log(statefulPattern.test("42")); // true
console.log(statefulPattern.lastIndex); // 2
console.log(statefulPattern.test("42")); // false
console.log(statefulPattern.lastIndex); // 0

const validationPattern = /^\d+$/;

console.log(validationPattern.test("42")); // true
console.log(validationPattern.test("42")); // true

Global and sticky regex objects retain their search position in lastIndex. A second call may start at the end of the previous match rather than at the beginning. On failure, the position resets to zero. [4]

The g flag can search forward from that position; y requires a match at the position itself. Avoid both for independent validation. i ignores case, m changes anchors, and s lets the dot match line terminators. [2]

How do you extract multiple records with named groups?

const log = "ERROR E101: Disk full\nERROR E205: Timeout";
const errorPattern = /^ERROR (?<code>E\d{3}): (?<message>[^\r\n]+)$/gm;

const errors = Array.from(log.matchAll(errorPattern), ({ groups }) => ({
  code: groups.code,
  message: groups.message,
}));

console.log(errors);
// [
//   { code: "E101", message: "Disk full" },
//   { code: "E205", message: "Timeout" },
// ]

With g, match() returns complete matches without capture groups. matchAll() instead provides an iterator containing match details; (?<code>...) gives a capture a meaningful name. A RegExp argument must have g. [5][6]

The example parses a defined log format, not arbitrary logs. m enables line-based matching. (?:...) groups a subpattern without capturing it, while \k<name> matches text previously captured under that name. matchAll() clones the regex but starts at its current lastIndex, so use a fresh pattern when starting from the beginning. [5][6]

How do you replace matches without losing data?

const text = "Open ticket #12 and ticket #34.";
const ticketPattern = /#(?<id>[0-9]+)/g;

const result = text.replace(ticketPattern, (match, id) => {
  return `TICKET-${id.padStart(5, "0")}`;
});

console.log(result); // Open ticket TICKET-00012 and ticket TICKET-00034.

A replace() callback receives the match and captured substrings and can transform each identifier. Without g, a regex argument to replace() replaces only the first match. [7]

padStart() keeps the identifier as a string, preserving leading zeros. Simple replacements can use $1 or $<id>. If replacement text comes from a user, returning it from a callback prevents sequences such as $& from being interpreted as replacement instructions. [7]

How do you handle Unicode letters and accents?

function extractWords(text) {
  const normalizedText = text.normalize("NFC");

  return normalizedText.match(/\p{L}[\p{L}\p{M}]*/gu) ?? [];
}

console.log(extractWords("Zażółć 東京 café"));
// ["Zażółć", "東京", "café"]

console.log(extractWords("cafe\u0301")); // ["café"]
console.log(extractWords("123")); // []

\w is not a universal letter class and \d covers ASCII digits. \p{L} matches Unicode letters and \p{M} combining marks; property escapes require u or v, which cannot be combined. NFC normalization makes canonically equivalent spellings consistent when that fits the domain. [8]

The example extracts runs of letters, not validated personal names or linguistically complete words. Unicode-aware matching operates on code points, not entire grapheme clusters. Use Intl.Segmenter when you need language-sensitive word or grapheme segmentation. [13]

How do you safely insert literal user text?

function containsLiteral(text, query) {
  if (query.length === 0) {
    return false;
  }

  return text.includes(query);
}

function createLiteralPattern(query) {
  if (typeof RegExp.escape !== "function") {
    throw new Error("RegExp.escape() requires a supported runtime");
  }

  return new RegExp(RegExp.escape(query), "gu");
}

console.log(containsLiteral("a.b", "a.b")); // true
console.log(containsLiteral("axb", "a.b")); // false

if (typeof RegExp.escape === "function") {
  console.log(createLiteralPattern("a.b").test("axb")); // false
  console.log(createLiteralPattern("a.b").test("a.b")); // true
}

Passing a.b directly to a regex constructor makes the dot a metacharacter. Use includes() for plain substring search. When composing a regex, RegExp.escape() encodes input as a literal pattern fragment. [9]

Older runtimes may not support this API. Detect it or use a specification-compliant polyfill rather than an improvised replacement expression. Escaping regex syntax neither sanitizes HTML nor fixes expensive matching in the surrounding pattern.

How do you prevent ReDoS and main-thread stalls?

function isTagList(value) {
  if (typeof value !== "string" || value.length > 256) {
    return false;
  }

  const tags = value.split(",");
  const tagPattern = /^[a-z0-9]{1,24}$/;

  if (tags.length > 10) {
    return false;
  }

  return tags.every((tag) => tagPattern.test(tag));
}

console.log(isTagList("css,javascript")); // true
console.log(isTagList("css,,javascript")); // false
console.log(isTagList("a".repeat(257))); // false

Overlapping quantifiers and ambiguous alternatives can trigger excessive backtracking, particularly on input that almost matches but fails near the end. Input limits help, but cannot substitute for simplifying the pattern. [11]

For a comma-separated tag list, split first and validate each bounded token. The example limits (256 UTF-16 code units, 10 tags and 24 ASCII characters per tag) are product rules, not universal thresholds. Test difficult inputs in an isolated worker or process with a deadline; a timer on the same thread cannot interrupt a synchronous regex.

How do you use regex in HTML forms?

<label for="order-id">Order ID</label>
<input
  id="order-id"
  name="orderId"
  type="text"
  pattern="ORD-[0-9]{6}"
  required
  aria-describedby="order-hint"
/>
<p id="order-hint">Example: ORD-012345</p>

Try the patterns in the POLPROG Regex Tester.

The HTML pattern attribute takes a pattern without enclosing slashes and matches the entire nonempty value. Modern HTML compiles it with v, which changes some character-class syntax compared with traditional regex patterns. required separately rejects empty input. [10]

Provide a visible format hint linked to the input. validity.patternMismatch exposes a format error, but browser validation is not a security boundary: repeat validation and business-rule checks on the server.

Regular expressions work well for well-defined textual formats. They do not replace parsers, business rules or server-side validation. Use includes for literal search, choose explicit boundaries for validators and test rejected input as carefully as accepted input.

Tools for this topic

JavaScript Regular Expressions Regex RegExp Unicode Input Validation ReDoS HTML Forms

Frequently asked questions

Why does test() alternate between true and false?

A successful global or sticky match updates lastIndex. Remove g and y for independent validation. [4]

Can regex prove an email address exists?

No. Format validation and mailbox ownership verification are separate tasks.

Does RegExp.escape prevent ReDoS?

It escapes literal input, but does not fix an expensive surrounding pattern. [9][11]

When should I use matchAll instead of match?

When you need every match and its capture groups. A RegExp argument must have the g flag. [5][6]

Sources and references

  1. MDN, Regular expressions guide↩
  2. MDN, Regular expression syntax↩
  3. MDN, Input boundary assertion↩1↩2
  4. MDN, RegExp.lastIndex↩1↩2↩3
  5. MDN, String.matchAll()↩1↩2↩3↩4
  6. MDN, Groups and backreferences↩1↩2↩3↩4
  7. MDN, String.replace()↩1↩2
  8. MDN, Unicode character class escapes↩1↩2
  9. MDN, RegExp.escape()↩1↩2↩3
  10. MDN, HTML pattern attribute↩
  11. OWASP, Denial of Service Cheat Sheet↩1↩2↩3
  12. MDN, RegExp constructor↩
  13. MDN, Intl.Segmenter↩

Was this helpful?

Get new articles by email

One short email per new Learning article. No spam, unsubscribe in one click.

We only use your email to send new articles. No third-party sharing.

Back to Learning