Skip to content

formatTemplate function ​

Replaces the {key} placeholders of a template with values. A placeholder without value is kept, so that it shows.

ts
import { formatTemplate } from 'utils';

Signature ​

ts
export function formatTemplate(
  template: string,
  values: Readonly<Record<string, boolean | number | string | undefined>>,
): string

Parameters ​

NameDescription
templateA text with {key} placeholders.
valuesThe values by key.

Returns ​

The text with every known placeholder replaced.

Example ​

ts
formatTemplate('Heading {heading}°, speed {speed} kn', { heading: 270, speed: 12.5 });
// 'Heading 270°, speed 12.5 kn'
formatTemplate('Hello {name}', {}); // 'Hello {name}'

Tests ​

Line coverage: 100 %.

  • ✅ replaces the placeholders
  • ✅ keeps the placeholders without a value
  • ✅ accepts dotted keys and ignores malformed placeholders

Source ​

src/string/format-template.ts (on GitHub)

Source code
ts
const PLACEHOLDER_PATTERN = /\{(?<key>[\w$.]+)\}/gv;

/**
 * Replaces the `{key}` placeholders of a template with values. A placeholder without value is kept, so that
 * it shows.
 *
 * @param template - A text with `{key}` placeholders.
 * @param values - The values by key.
 * @returns The text with every known placeholder replaced.
 * @example
 * formatTemplate('Heading {heading}°, speed {speed} kn', { heading: 270, speed: 12.5 });
 * // 'Heading 270°, speed 12.5 kn'
 * formatTemplate('Hello {name}', {}); // 'Hello {name}'
 */
export function formatTemplate(
  template: string,
  values: Readonly<Record<string, boolean | number | string | undefined>>,
): string {
  return template.replaceAll(PLACEHOLDER_PATTERN, (placeholder: string, key: string) => {
    const value = Object.hasOwn(values, key) ? values[key] : undefined;
    return value === undefined ? placeholder : String(value);
  });
}
Test file
ts
import { formatTemplate } from './format-template';

describe(formatTemplate, () => {
  it('replaces the placeholders', () => {
    expect(formatTemplate('Heading {heading}°, speed {speed} kn', { heading: 270, speed: 12.5 })).toBe(
      'Heading 270°, speed 12.5 kn',
    );
    expect(formatTemplate('{a}{a}{b}', { a: 'x', b: true })).toBe('xxtrue');
  });

  it('keeps the placeholders without a value', () => {
    expect(formatTemplate('Hello {name}', {})).toBe('Hello {name}');
    expect(formatTemplate('Hello {name}', { name: undefined })).toBe('Hello {name}');
    expect(formatTemplate('{toString}', {})).toBe('{toString}');
  });

  it('accepts dotted keys and ignores malformed placeholders', () => {
    expect(formatTemplate('{user.name} { } {}', { 'user.name': 'Ada' })).toBe('Ada { } {}');
  });
});

Keywords: format, template, strings, function

Generated from the JSDoc of the sources.