String Interpolation
JavaScript
/*
String Interpolation Syntax
The regex /\$\{(\w+)\}/g finds all substrings of the form {XYZ}.
Whenever such a pattern is found, the function in the 2nd parameter of .replace will be called to get the replacement.
It will search the associative array and try to return that replacement if the key exists (reps[key]).
Otherwise, the original substring (s) will be returned, i.e. nothing is replaced. (See In Javascript, what does it mean when there is a logical operator in a variable declaration? for how || makes this work.)
*/
var reps = { //replacements
a: "pesky",
b: "monkey",
c: "banana"
};
var str = "The ${a} ${b} took my ${c}!";
str = str.replace(/\$\{(\w+)\}/g, function(s, key) {
return reps[key] || s;
});
document.write(str + "<br>");
interpStr = function (str, reps) {
for(key in reps) {
if(reps.hasOwnProperty(key)) {
str = str.replace(/\$\{(\w+)\}/, reps[key]);
}
}
return str;
};
var str2 = "Can you believe that ${a} used to be a ${b}."
var rep1 = "bob";
var rep2 = "girl";
str2 = interpStr(str2,{a:rep1, b:rep2});
document.write(str2);