AniUI Academy

Interpolate a mustache-style template

mediumDOM & Utilities+250 XPPractice

Email templates, i18n strings and CMS snippets all use some flavour of {{ placeholder }}. Writing the interpolator yourself is a five-minute job that teaches you exactly why the real ones are careful about missing keys.

Implement interpolate(template, data). Replace every placeholder of the form {{ path }} — where whitespace immediately inside the braces is ignored and path is made of letters, digits, _, $ and . — with the resolved value from data.

A path is resolved by splitting on . and walking data segment by segment, so user.name reads data.user.name and items.0.title reads data.items[0].title. If the walk hits null or undefined at any point, or the final value is null or undefined, the placeholder is replaced with the empty string.

Other values are inserted with String(value), so 0 renders as "0" and false as "false". Text that is not a complete placeholder — including a {{ with no closing }} — is left exactly as it is, and inserted values are never scanned for further placeholders.

Arguments

templatestring
The template text with {{ path }} placeholders. Whitespace inside the braces is ignored.
dataobject
The object whose values resolve the placeholders. Dotted paths walk into nested objects and arrays.

Returns

string — The template with every placeholder replaced. Missing paths render as ""; inserted values are never re-scanned.

Examples

interpolate("Hello {{ name }}!", { name: "Ada" });
// => "Hello Ada!"

Whitespace inside the braces is ignored.

interpolate("{{user.name}} <{{user.email}}>", {
  user: { name: "Ada", email: "[email protected]" }
});
// => "Ada <[email protected]>"

Dotted paths walk into nested objects.

interpolate("Hi {{missing}}{{a.b.c}}.", {});
// => "Hi ."

A missing path renders as the empty string, not as undefined.

What it has to do

  • Replace every {{ path }} placeholder, ignoring whitespace inside the braces.
  • Resolve dotted paths, including numeric segments that index arrays.
  • Replace a missing, null or undefined value with the empty string.
  • Insert other values with String(value), so 0 and false render as text.
  • Leave unclosed or malformed braces untouched and never re-interpolate inserted text.

Notes

  • One global .replace with a callback is what prevents re-interpolation: the regex only looks at the original template, never at the strings the callback produced.
  • This interpolator does not escape the inserted values. If the output ends up in HTML you still need to combine it with an escapeHtml step on each value.

Stuck? The javascript course covers everything this challenge needs.

Try it yourself
Loading playground...
5 tests · +250 XP

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.