Write a tiny template engine. Replace every placeholder of the form {{name}} in the template with the matching value from a JSON object.
- A placeholder is
{{, optional spaces, a name, optional spaces,}}. A name starts with a letter or_and continues with letters, digits or_. - Values are strings or integers; print integers in normal decimal form.
- If the name is not in the object, leave the placeholder exactly as it was written.
- Scan from left to right; text that is not a valid placeholder is copied unchanged.
Constraints
- The template is one line of at most 2000 characters.
- The JSON object is one line of at most 2000 characters.
Input and output
- Input
- Line 1: the template Line 2: a JSON object of values
- Output
- One line: the rendered text.
Examples
Input 1
Hello {{name}}, your rank is {{ rank }}.
{"name":"Asha","rank":42}Output
Hello Asha, your rank is 42.Spaces inside the braces are allowed.
Input 2
Dear {{name}}, fee due: {{fee}}
{"name":"Ravi"}Output
Dear Ravi, fee due: {{fee}}Unknown names are left exactly as written.
Show hints
- One global regular expression with a capture group and a replacer function does all the work.
Show the explanation
Use String.prototype.replace with a global regex and a replacer function:
tpl.replace(/\{\{ *([A-Za-z_][A-Za-z0-9_]*) *\}\}/g,
(whole, name) => (Object.hasOwn(values, name) ? String(values[name]) : whole));The regex engine scans left to right and resumes after each match, which is exactly the required behaviour; for {{{name}}} the first brace cannot start a match, so the placeholder starting at the second brace is replaced and the outer braces stay.
Object.hasOwn (rather than values[name] !== undefined) avoids picking up inherited names like toString. In real apps, remember to HTML-escape values before inserting them into markup, or the template engine becomes an XSS hole.
Original UniCircle question. Last reviewed 22 Oct 2026.
