How can I do string interpolation in JavaScript?

前端 未结 19 2506
慢半拍i
慢半拍i 2020-11-21 07:54

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

19条回答
  •  攒了一身酷
    2020-11-21 08:01

    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.

提交回复
热议问题