2.7 KiB
escape
Purpose
Provides three utility functions for handling escape sequences in template strings. These are low-level primitives used internally by the engine and exported for consumers who need to pre-process or post-process template content.
The escape module is intentionally stateless and side-effect free — each function is a pure transformation of its input string with no I/O or global state.
Features
escapeRegex(str)— escapes all regex metacharacters for safe embedding inRegExpconstructors.unescapeTemplate(str)— removes backslash escapes from\{and\}sequences after rendering.isEscaped(str, pos)— determines whether a character at a given position is preceded by an odd number of backslashes (i.e., is actually escaped).
Usage: Basic Example
import { escapeRegex, unescapeTemplate } from "@suaveplan/templates";
const safe = escapeRegex("user.name"); // "user\\.name"
const re = new RegExp(`\\{${safe}\\}`, "g");
const result = unescapeTemplate("Say \\{hello\\}"); // "Say {hello}"
Usage: Advanced Example
import { isEscaped, unescapeTemplate } from "@suaveplan/templates";
// Custom pre-processing: skip escaped tokens
function tokenize(template: string): string[] {
const tokens: string[] = [];
const re = /\{[^}]+\}/g;
let m: RegExpExecArray | null;
while ((m = re.exec(template)) !== null) {
if (!isEscaped(template, m.index)) {
tokens.push(m[0]);
}
}
return tokens;
}
// After rendering, strip escape sequences
const rendered = renderSomehow(template);
const final = unescapeTemplate(rendered);
API Reference
escapeRegex(str: string): string
Escapes all characters that have special meaning in a regular expression: . * + ? ^ $ { } ( ) | [ ] \. Returns a string safe to pass to new RegExp(str).
unescapeTemplate(str: string): string
Replaces \{ with { and \} with } throughout str. Other backslash sequences are left unchanged.
isEscaped(str: string, pos: number): boolean
Returns true when the character at pos is preceded by an odd number of consecutive backslashes. An even count means the backslashes escape each other and the character at pos is not escaped.
Implementation Notes
isEscapedcounts backslashes by walking backwards frompos - 1until a non-backslash character (or the start of the string) is found. The parity of the count determines whether the target character is escaped.unescapeTemplateuses a single regex pass — O(n) regardless of the number of escape sequences.escapeRegexuses the standard replace idiom which covers all metacharacters recognised by ECMAScript RegExp grammar.