Skip to content

@kaelyx/ts-kit / string / template

Function: template() ​

template(input, variables, options?): string

Defined in: string/template/template.ts:35

Replaces the placeholders in a string with values from variables.

The first capture group of placeholderPattern is the variable name. A placeholder is unknown if variables has no own key with that name.

Parameters ​

input ​

string

The template. An empty string returns an empty string.

variables ​

Record<string, unknown>

The values to use. Each value is converted with String().

options? ​

TemplateOptions

How to replace placeholders and what to do with unknown placeholders.

Returns ​

string

A new string with the placeholders replaced.

Throws ​

If unknownBehaviour is TemplateOptionsUnknownBehaviour.throw and the input contains an unknown placeholder.

Example ​

ts
template('Hello, {{name}}!', { name: 'Ada' }) // 'Hello, Ada!'
template('{{count}} items, in stock: {{inStock}}', { count: 3, inStock: true }) // '3 items, in stock: true'
template('{{a}} {{b}}', { a: 1 }) // '1 {{b}}'
template('{{a}} {{b}}', { a: 1 }, { unknownBehaviour: TemplateOptionsUnknownBehaviour.remove }) // '1 '
template('{{a}}', {}, { unknownBehaviour: TemplateOptionsUnknownBehaviour.throw }) // throws Error
template('{{a}} {{a}}', { a: 1 }, { replaceBehaviour: TemplateOptionsReplaceBehaviour.replaceFirst }) // '1 {{a}}'
template('Hello, ${name}!', { name: 'Ada' }, { placeholderPattern: /\$\{(\w+)\}/ }) // 'Hello, Ada!'

Types ​

TemplateOptionsReplaceBehaviour type ​

TemplateOptionsReplaceBehaviour = ValueOf<typeof TemplateOptionsReplaceBehaviour>

Defined in: string/template/template.types.ts:7

The behavior for how replacements are applied.


TemplateOptionsUnknownBehaviour type ​

TemplateOptionsUnknownBehaviour = ValueOf<typeof TemplateOptionsUnknownBehaviour>

Defined in: string/template/template.types.ts:15

The behavior for how unknown placeholders are handled.


TemplateOptions interface ​

Defined in: string/template/template.types.ts:33

Options for configuring template behavior.

Properties ​

placeholderPattern? ​

optional placeholderPattern?: RegExp

Defined in: string/template/template.types.ts:38

Placeholder Pattern

Default ​
ts
/{{(\w+)}}/g

replaceBehaviour? ​

optional replaceBehaviour?: "REPLACE_ALL" | "REPLACE_FIRST"

Defined in: string/template/template.types.ts:35

Determines how replacements are applied.

Default ​
ts
TemplateOptionsReplaceBehaviour.replaceAll

unknownBehaviour? ​

optional unknownBehaviour?: "IGNORE" | "REMOVE" | "THROW"

Defined in: string/template/template.types.ts:41

Determines what the function does if it encounters an unknown placeholder.

Default ​
ts
TemplateOptionsUnknownBehaviour.ignore