Skip to content

Instantly share code, notes, and snippets.

@culshaw
Last active September 13, 2016 09:21
Show Gist options
  • Save culshaw/7648304b1e6008c069cf28913fab0655 to your computer and use it in GitHub Desktop.
Save culshaw/7648304b1e6008c069cf28913fab0655 to your computer and use it in GitHub Desktop.
javascript:Template literal parser for non es6 strings
function interpolate(text, literals) {
return text.replace(new RegExp(/\$\{(\w+)\}/, "g"), function() {
if(arguments[1] in literals) {
return literals[arguments[1]];
}
throw new Error("Literal "+arguments[1]+" doesn't exist for text replacement");
});
}
@culshaw
Copy link
Author

culshaw commented Sep 7, 2016

In ES6 this would be parsed fine

var myDictOfVars = {
    'user_name': "Clarence",
    'person_of_interest': "David"
}; 

var enWelcomeString = `Hi ${myDictOfVars.user_name}, did you enjoy the beach with ${myDictOfVars.person_of_interest}?`;
var deWelcomeString = `Hallo, Magst du den Strand mit ${myDictOfVars.person_of_interest}, ${myDictOfVars.username}?`;

An example

var myDictOfVars = {
    'user_name': "Clarence",
    'person_of_interest': "David"
}; 

var enWelcomeString = _("Hi ${user_name}, did you enjoy the beach with ${person_of_interest}?", myDictOfVars);
var deWelcomeString = _("Hallo, Magst du den Strand mit ${person_of_interest}, ${username}?", myDictOfVars);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment