Skip to content

Instantly share code, notes, and snippets.

@darkmavis1980
Created March 3, 2020 16:46
Show Gist options
  • Save darkmavis1980/2b9a4ba6946ac532b641c73de1864323 to your computer and use it in GitHub Desktop.
Save darkmavis1980/2b9a4ba6946ac532b641c73de1864323 to your computer and use it in GitHub Desktop.
Format a string with variables passed as an object
function format(string, keyValues) {
const regex = /{{([a-zA-Z]+)}}/g;
return string.replace(regex, (match, key) => {
return keyValues[key];
});
}
console.log(format('Hello {{name}}', {name: 'Alessio'})); // Hello Alessio
console.log(format('The price is {{currency}} {{price}}', {price: '10.5', currency: 'EUR'})); // The price is EUR 10.5
console.log(format('Il prezzo è {{price}}{{currency}}', {price: '10.5', currency: 'EUR'})); // Il prezzo è 10.5EUR
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment