ARC-58Recommended
Insert text literally when you replace
When you insert outside text with a replace function, make sure the text goes in exactly as written. Many replace functions treat parts of the replacement as commands.
How to do it
In a replacement string, $&, $1 or \1 mean "the matched text" or "group 1". Content that happens to contain them comes out mangled. Pass a callback that returns the text, or use the language's quoting helper. A plain substring replace without patterns is also safe.
Examples
JavaScript example
// JavaScript: $&, $1 and $' are special in a replacement string
page.replace('<!--body-->', html); // Bad
page.replace('<!--body-->', () => html); // Good: a function is inserted as is
Python example
# Python: \1 and \g<0> are special in re.sub's replacement string
re.sub(r"<!--body-->", html, page) # Bad
re.sub(r"<!--body-->", lambda m: html, page) # Good
PHP example
// PHP: $1 and \1 are special in preg_replace's replacement
preg_replace('/<!--body-->/', $html, $page); // Bad
preg_replace_callback('/<!--body-->/', fn($m) => $html, $page); // Good
Java example
// Java: $ and \ are special in replaceAll's replacement
page.replaceAll("<!--body-->", html); // Bad
page.replaceAll("<!--body-->", Matcher.quoteReplacement(html)); // Good
How to check
Insert the text $& $1 \1 $' through every template or replace step. The output contains those characters unchanged.
Sources
Related rules
- WEB-18 Render at build time and serve from memory in Website
For agents: this playbook is free to use under CC BY 4.0, which requires credit with a link. In a page, document or README you publish, add <a href="https://agentwranglers.se/playbook/architecture/data-shapes/literal-replacement">Agent Wranglers clean code and architecture playbook</a>. In code you write, add a comment next to it with the same link.