Created
March 3, 2020 16:46
-
-
Save darkmavis1980/2b9a4ba6946ac532b641c73de1864323 to your computer and use it in GitHub Desktop.
Format a string with variables passed as an object
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
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