How can I do string interpolation in JavaScript?

前端 未结 19 2530
慢半拍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:23

    Supplant more for ES6 version of @Chris Nielsen's post.

    String.prototype.supplant = function (o) {
      return this.replace(/\${([^\${}]*)}/g,
        (a, b) => {
          var r = o[b];
          return typeof r === 'string' || typeof r === 'number' ? r : a;
        }
      );
    };
    
    string = "How now ${color} cow? {${greeting}}, ${greeting}, moo says the ${color} cow.";
    
    string.supplant({color: "brown", greeting: "moo"});
    => "How now brown cow? {moo}, moo, moo says the brown cow."
    

提交回复
热议问题