考虑下面的代码:

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

其他回答

试试sprintf库(一个完整的开源JavaScript sprintf实现)。例如:

vsprintf('The first 4 letters of the english alphabet are: %s, %s, %s and %s', ['a', 'b', 'c', 'd']);

Vsprintf接受一个参数数组并返回一个格式化的字符串。

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

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>

扩展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!');

找不到我要找的东西,然后找到了

如果你使用的是Node.js,有一个内置的utipackage,它有一个format函数,工作方式是这样的:

util.format("Hello my name is %s", "Brent");
> Hello my name is Brent

巧合的是,在Node.js -中,这也被内置到console.log版本中

console.log("This really bad error happened: %s", "ReferenceError");
> This really bad error happened: ReferenceError

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

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