My learning diary

String.format equivalent in TypeScript

While working on a problem during work, I thought I needed a way to do a String.format equivalent operation in TypeScript (it turns out I didn’t need to). I didn’t want to install Lodash (50 kB for _.template alone) or sprintf (40 kB), so I came up with the following:

// Warning: Untested code
export const compileTemplate = (template: string, values: Map<string, string>) => {
    const variables = Array.from(values.keys()).map(key => ':' + key).join('|');
    return template.replace(
        new RegExp(variables, 'g'),
        (match: string) => values.get(match.substr(1)) ?? match
    );
};

There are the Stack Overflow threads I consulted:

Relevant posts