String Template Parser

MediumUtility Functions15 min4 tests

Implement a template function that replaces placeholders in a string with values from a data object.

Requirements

  • Placeholders use the format {key}
  • Replace all occurrences of each placeholder
  • Leave unmatched placeholders unchanged
  • Handle nested keys is NOT required

Example

template("Hello {name}!", { name: "World" }); // "Hello World!"
template("{a} + {b} = {c}", { a: "1", b: "2", c: "3" }); // "1 + 2 = 3"
Hints (4)
  1. Use a regular expression to find all placeholders in the format {key}.
  2. The regex /\{(\w+)\}/g captures the key name inside the braces.
  3. Use String.prototype.replace with a callback function.
  4. Check if the key exists in the data object before replacing.

Topics

  • Utility Functions

Asked at

Shopify · Stripe · Atlassian

Join Us
blur