String Template Interpolation With Missing Key Errors
Render double-brace placeholders from a plain object, raising clear errors for missing keys instead of silently printing undefined.
Code
export function interpolate(template, values) {
if (typeof template !== "string") throw new TypeError("template must be a string");
if (values === null || typeof values !== "object") {
throw new TypeError("values must be an object");
}
return template.replace(/\{\{\s*([\w.]+)\s*\}\}/g, (match, key) => {
if (!Object.prototype.hasOwnProperty.call(values, key)) {
throw new RangeError('missing value for "' + key + '"');
}
const value = values[key];
if (value === null || value === undefined) {
throw new TypeError('nullish value for "' + key + '"');
}
return String(value);
});
}Report a problem with this exampleOpens a pre-filled issue on GitHub.