考虑下面的代码:

var age = 3;

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

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


当前回答

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

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

其他回答

下面是一个解决方案,它要求您提供一个具有值的对象。如果你不提供一个对象作为参数,它将默认使用全局变量。但是最好还是使用参数,这样更简洁。

String.prototype.interpolate = function(props) { return this.replace(/\{(\w+)\}/g, function(match, expr) { return (props || window)[expr]; }); }; // Test: // Using the parameter (advised approach) document.getElementById("resultA").innerText = "Eruption 1: {eruption1}".interpolate({ eruption1: 112 }); // Using the global scope var eruption2 = 116; document.getElementById("resultB").innerText = "Eruption 2: {eruption2}".interpolate(); <div id="resultA"></div><div id="resultB"></div>

试试kiwi吧,它是一个轻量级的JavaScript模块,用于字符串插值。

你可以这样做

Kiwi.compose("I'm % years old!", [age]);

or

Kiwi.compose("I'm %{age} years old!", {"age" : age});

如果您想在console.log输出中插入,那么只需

console.log("Eruption 1: %s", eruption1);
                         ^^

这里,%s是所谓的“格式说明符”。log内置了这种插值支持。

替换更多的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."

我可以给你们举个例子:

函数fullName(first, last) { let fullName = first + " " + last; 返回fullName; } 函数fullNameStringInterpolation(first, last) { let fullName = ' ${first} ${last} '; 返回fullName; } console.log('Old School: ' + fullName('Carlos', 'Gutierrez')); console.log('New School: ' + fullNameStringInterpolation('Carlos', 'Gutierrez'));