Skip to content

template

Interpolates {{key}} placeholders in a template string with values from a data record. Unknown keys are replaced with an empty string.

No eval or Function constructor is used — substitution is purely regex-based. Nested expressions and logic are intentionally out of scope.

Available since v2.0.0

import { template } from '@helpers4/string';
template(str: string, data: Record<string, unknown>): string
ParameterTypeDescription
strstringThe template string containing {{key}} placeholders.
dataRecord<string, unknown>A record mapping placeholder names to replacement values.

string — The template string with all placeholders replaced.

Replaces {{key}} placeholders with values from the data object.

template('Hello, {{name}}!', { name: 'Alice' })
// => 'Hello, Alice!'

All matching placeholders are replaced in a single pass.

template('{{greeting}}, {{name}}!', { greeting: 'Hi', name: 'Bob' })
// => 'Hi, Bob!'

Unknown placeholders are replaced with an empty string.

template('Hello, {{name}}!', {})
// => 'Hello, !'

View source on GitHub