Format a string
Replace {0}, {1}… placeholders with values in order.
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.
Keep exploring
- Capitalize a string — Uppercase the first Unicode code point and preserve the remaining text.
- Reverse a string — Reverse Unicode code points without splitting surrogate pairs.
- Check a palindrome — Compare a string with its code-point reversal.