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:
- Can ES6 template literals be substituted at runtime (or reused)?
- Defer execution for ES6 Template Literals
- Convert a string to a template string
- String.Format in Javascript?
- lodash _.template alternative native
- Pass a JS Object as the scope to a JS Template Literal?
- How do I destructure all properties into the current scope/closure in ES2015? (but MDN does not recommend this approach)