Consider this code:
var age = 3;
console.log(\"I\'m \" + age + \" years old!\");
Are there any other ways to insert the value of a variabl
Douglas Crockford's Remedial JavaScript includes a String.prototype.supplant
function. It is short, familiar, and easy to use:
String.prototype.supplant = function (o) {
return this.replace(/{([^{}]*)}/g,
function (a, b) {
var r = o[b];
return typeof r === 'string' || typeof r === 'number' ? r : a;
}
);
};
// Usage:
alert("I'm {age} years old!".supplant({ age: 29 }));
alert("The {a} says {n}, {n}, {n}!".supplant({ a: 'cow', n: 'moo' }));
If you don't want to change String's prototype, you can always adapt it to be standalone, or place it into some other namespace, or whatever.