Skip to content

Instantly share code, notes, and snippets.

@marlun78
Created July 19, 2018 12:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marlun78/be72d2cba822df8c3b7977601a163c98 to your computer and use it in GitHub Desktop.
Save marlun78/be72d2cba822df8c3b7977601a163c98 to your computer and use it in GitHub Desktop.
Replaces placeholders in a string template with passed values
// interpolate.js
// Based on Crockford’s supplant (http://www.crockford.com/javascript/remedial.html)
// Example;
// interpolate('Hello {name}!', { name: 'Martin' }); // 'Hello Martin!'
// interpolate('Hello {0}!', ['Vanja']); // 'Hello Vanja!'
function interpolate(template, values) {
return template.replace(/\{([^{}]*)\}/g, function(match, key) {
const value = values[key];
const type = typeof value;
return type === 'string' || type === 'number' ? value : match;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment