Skip to content
Onsite

Template String Interpolation

MediumP3Coding

Implement interpolate(template, data), which replaces {{path}} placeholders in a string with values from data.

  • A placeholder is {{, a path, }}. Spaces around the path are ignored: {{ user.name }} equals {{user.name}}.
  • A path is dot-separated keys, with optional array indexes: user.name, items[0].title, items.0.title.
  • The replacement is String(value), so 0 becomes "0" and false becomes "false".
  • If the path does not exist, or the value is null or undefined, the placeholder becomes the empty string.
  • Text that is not a complete placeholder (an unclosed {{, a single brace) is left unchanged. Replaced values are not scanned again for placeholders.
  • Never evaluate code; only read properties.

Example 1

Input
interpolate('Hi {{ user.name }}, you have {{count}} items', { user: { name: 'Ada' }, count: 3 })
Output
'Hi Ada, you have 3 items'

Constraints

  • 0 <= template.length <= 10^5

Hints

Run checks the 3 visible tests, Submit all 11.