Created
July 19, 2018 12:25
-
-
Save marlun78/be72d2cba822df8c3b7977601a163c98 to your computer and use it in GitHub Desktop.
Replaces placeholders in a string template with passed values
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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