Files
skills/docs/localization/i18n/i18n-icu-parser/src/interpolation/escape-regex.md
2026-05-29 08:20:56 +01:00

3.1 KiB

escape-regex

Purpose

escapeRegex escapes every regular-expression metacharacter in a string so the string can be embedded literally inside a RegExp constructor. The {@link InterpolationEngine} uses it to compile placeholder patterns from caller-supplied delimiters ({{, %{, <%, …) into a working RegExp without inadvertently treating delimiter characters as regex syntax. Exposing it as a standalone export lets downstream consumers build their own delimiter-aware patterns or sanitise raw search queries.

The helper lives in its own file (alongside escape-html) so tree-shaking can strip the rest of the interpolation engine when a consumer needs only the escape primitive — for example, a documentation tooling pipeline that compiles user-typed search patterns into a forgiving regex.

Features

  • Escapes the canonical 12 ECMAScript regex metacharacters (. * + ? ^ $ { } ( ) | [ ] \) plus the closing brace
  • Pure function: no I/O, no state, deterministic per input
  • Single-pass String.prototype.replace with a precompiled regex literal — no allocation beyond the output string
  • Zero dependencies — drops cleanly into edge / worker bundles

Usage: Basic Example

import { escapeRegex } from "@suaveplan/i18n-icu-parser/interpolation";

const safe = escapeRegex("a.b*c");
// "a\\.b\\*c"
const re = new RegExp(safe);
re.test("a.b*c"); // true (literal match)

Usage: Advanced Example

import { escapeRegex } from "@suaveplan/i18n-icu-parser/interpolation";

// Build a placeholder pattern from caller-supplied delimiters.
function buildPlaceholderPattern(open: string, close: string): RegExp {
    const o = escapeRegex(open);
    const c = escapeRegex(close);
    return new RegExp(`${o}\\s*([^${c}]+)\\s*${c}`, "g");
}

const re = buildPlaceholderPattern("<%=", "%>");
const matches = "Hello <%= name %>".matchAll(re);
for (const m of matches) console.log(m[1]?.trim()); // "name"

API Reference

escapeRegex(str: string): string

Escape every regular-expression metacharacter in str. The escaped output can be inserted unchanged into a RegExp source string and will match the original character literally.

Escaped characters: ., *, +, ?, ^, $, {, }, (, ), |, [, ], \.

Returns: the escaped string. Strings without metacharacters return unchanged.

Implementation Notes

  • The replacement uses \\$& (backref to the whole match) rather than enumerating every escape sequence, which keeps the function bytes-small and easy to audit.
  • The character class [.*+?^${}()|[\\]\\\\] is the canonical V8 / SpiderMonkey escape set for the standard RegExp grammar. Alternation operators inside character classes (-) do NOT need escaping at the outer level and are intentionally omitted.
  • The function is O(n) in input length. Worst case is a string of only metacharacters which expands 2x in the output.
  • This is the canonical regex escape across Suaveplan — every package that needs to embed user input in a RegExp consumes this helper or its inlined twin in the parser file.