Is there an easier way than "I'm " + age + " years old!"
views:
535answers:
5
+2
A:
Other than possibly eval()ing it which would be preposterous and evil, that should be the only way. IMO it's better because it's more clear and you don't have to deal with some strings that are interpolated versus some that aren't ( in PHP ) and it's faster.
meder
2009-09-10 23:42:33
+2
A:
You could use Prototype's template system if you really feel like using a sledgehammer to crack a nut:
var template = new Template("I'm #{age} years old!");
alert(template.evaluate({age: 21}));
brownstone
2009-09-10 23:48:49
+1
A:
You could code your own String.format() method. You can also use this one
codymanix
2009-09-10 23:50:01
+10
A:
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.
Chris Nielsen
2009-09-11 00:04:19
Note: This will run ten times slower than just concatenating.
roosteronacid
2009-09-11 07:00:27