Format a string

Replace {0}, {1}… placeholders with values in order.

JavaScript Version 1.0.0 · MIT · .md

format-a-string.js
function format({ template, values }) { return values.reduce((text, value, i) => text.replaceAll(`{${i}}`, String(value)), template); }

Input & expected output

Input

{
  "template": "Order {0} ships to {1}",
  "values": [
    "8812",
    "[email protected]"
  ]
}

Expected output

"Order 8812 ships to [email protected]"

The edge case

Input

{
  "template": "{0}{0}",
  "values": [
    "ab"
  ]
}

Expected output

"abab"

Know the limits

  • Replacements run in order, so a value containing "{1}" is replaced again by the next value. Use a template engine with escaping for HTML.

The function above is the implementation used by the lab. The lab validates JSON types and caps size before execution; include equivalent validation when accepting untrusted input in your application.

Source & maintenance

Based on Format a string from the original 1loc collection by Nguyen Huu Phuoc, with david-luna. Copyright (c) 2020 phuoc-ng. MIT licensed.

Uses replaceAll instead of building a RegExp per placeholder; takes template and values as one object. Original MDX retained as inert source evidence.

Maintained by Oveyon. Source commit: 14b481cf60df. Read the license.

Local fixture scope · Node.js 22.23.2 · reviewed October 28, 2026. No external service is required.

Keep exploring

Type two or more characters. Try “duplicate”, “webhook” or “retry”.