tags:

views:

535

answers:

5

Is there an easier way than "I'm " + age + " years old!"

+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
+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
+2  A: 

Try sprintf.

NawaMan
+1  A: 

You could code your own String.format() method. You can also use this one

codymanix
+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
Note: This will run ten times slower than just concatenating.
roosteronacid