考虑下面的代码:

var age = 3;

console.log("I'm " + age + " years old!");

除了字符串连接之外,还有其他方法可以将变量的值插入到字符串中吗?


当前回答

替换更多的ES6版本的@Chris Nielsen的帖子。

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."

其他回答

Douglas Crockford的remedy JavaScript包含一个String.prototype.supplant函数。它短小,熟悉,易于使用:

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' }));

如果你不想改变String的原型,你总是可以把它调整成独立的,或者把它放在其他的名称空间里,等等。

你可以使用Prototype的模板系统,如果你真的想用大锤敲开一个坚果:

var template = new Template("I'm #{age} years old!");
alert(template.evaluate({age: 21}));

扩展Greg Kindel的第二个答案,你可以写一个函数来消除一些样板文件:

var fmt = {
    join: function() {
        return Array.prototype.slice.call(arguments).join(' ');
    },
    log: function() {
        console.log(this.join(...arguments));
    }
}

用法:

var age = 7;
var years = 5;
var sentence = fmt.join('I am now', age, 'years old!');
fmt.log('In', years, 'years I will be', age + years, 'years old!');

在旧的浏览器中使用模板语法会失败,这对于创建供公众使用的HTML很重要。使用连接是乏味且难以阅读的,特别是当您有很多或很长的表达式时,或者如果您必须使用括号来处理数字和字符串项的混合(两者都使用+运算符)。

PHP扩展带引号的字符串,其中包含变量,甚至一些表达式,使用非常紧凑的符号:$a="颜色是$color";

在JavaScript中,可以编写一个有效的函数来支持这一点:var a=S('the color is ',color);,使用可变数量的参数。虽然在本例中没有连接的优势,但当表达式变长时,语法可能会更清晰。或者可以像在PHP中那样,使用JavaScript函数使用美元符号表示表达式的开始。

另一方面,编写一个有效的变通函数来为旧浏览器提供类似模板的字符串展开并不困难。可能已经有人这么做了。

最后,我认为sprintf(就像在C、c++和PHP中一样)可以用JavaScript编写,尽管它的效率要比其他解决方案低一些。

let age = 3;

console.log(`I'm ${age} years old!`);

你可以使用反撇号' '和ES6模板字符串