JavaScript Snippet

Tiny Template String Formatter

Difficulty: Medium

Sometimes you need a templating helper that does not pull in handlebars or eta, just enough to substitute `{name}` placeholders against a values object. This snippet starts with a 5-line interpolator, adds escape support so literal braces survive, and ends with a tagged-template-literal version that gives you compile-time placeholder safety. Drop it into i18n strings, log formatters, or email subject lines.

Code Snippets
/

Tiny Template String Formatter

Tiny Template String Formatter

Sometimes you need a templating helper that does not pull in handlebars or eta, just enough to substitute `{name}` placeholders against a values object. This snippet starts with a 5-line interpolator, adds escape support so literal braces survive, and ends with a tagged-template-literal version that gives you compile-time placeholder safety. Drop it into i18n strings, log formatters, or email subject lines.

JavaScript
Medium
3 snippets
strings
regex
js-template-literals
code-template

428 views

14

The pattern \{(\w+)\} captures one identifier-like token between braces, and replace runs once per match. Falling back to the original match when the key is absent leaves the placeholder visible, which is usually what you want during development because it surfaces missing translation keys instead of silently emitting 'undefined'. Numbers, booleans, and other primitives get coerced to strings via String(values[key]), so passing { amount: 19.99 } works without ceremony. Reach for this whenever you need template-style strings in a CLI tool, an i18n shim, or a log formatter.