Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | 1x 6x 9x 9x | 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);
});
}
|