# Format a string

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

Canonical: https://1loc.dev/string/format-a-string/
Version: 1.0.0
Runtime: JavaScript · Node.js 22 / modern browsers
Verification: Local fixtures; no external services
Updated: 2026-10-28

## Implementation

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

## Input

```json
{
  "template": "Order {0} ships to {1}",
  "values": [
    "8812",
    "ana@example.com"
  ]
}
```

## Expected output

```json
"Order 8812 ships to ana@example.com"
```

## Edge case

Input:
```json
{
  "template": "{0}{0}",
  "values": [
    "ab"
  ]
}
```
Output:
```json
"abab"
```

## 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 lab validates types and size before calling this function. Add equivalent validation at your own trust boundary.

## Source and license

Original: https://github.com/phuocng/1loc/blob/14b481cf60dff1620ab1bb99a43b1f68068cdd9b/contents/format-a-string.mdx
Author: Nguyen Huu Phuoc and original contributors
Contributors: david-luna
Source commit: 14b481cf60dff1620ab1bb99a43b1f68068cdd9b
Copyright (c) 2020 phuoc-ng
License: MIT — https://1loc.dev/licenses/
Maintainer: Oveyon
Modifications: Uses replaceAll instead of building a RegExp per placeholder; takes template and values as one object. Original MDX retained as inert source evidence.
