考虑下面的代码:

var age = 3;

console.log("I'm " + age + " 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}));

自定义灵活插补:

var sourceElm = document.querySelector('input') // interpolation callback const onInterpolate = s => `<mark>${s}</mark>` // listen to "input" event sourceElm.addEventListener('input', parseInput) // parse on window load parseInput() // input element parser function parseInput(){ var html = interpolate(sourceElm.value, undefined, onInterpolate) sourceElm.nextElementSibling.innerHTML = html; } // the actual interpolation function interpolate(str, interpolator = ["{{", "}}"], cb){ // split by "start" pattern return str.split(interpolator[0]).map((s1, i) => { // first item can be safely ignored if( i == 0 ) return s1; // for each splited part, split again by "end" pattern const s2 = s1.split(interpolator[1]); // is there's no "closing" match to this part, rebuild it if( s1 == s2[0]) return interpolator[0] + s2[0] // if this split's result as multiple items' array, it means the first item is between the patterns if( s2.length > 1 ){ s2[0] = s2[0] ? cb(s2[0]) // replace the array item with whatever : interpolator.join('') // nothing was between the interpolation pattern } return s2.join('') // merge splited array (part2) }).join('') // merge everything } input{ padding:5px; width: 100%; box-sizing: border-box; margin-bottom: 20px; } *{ font: 14px Arial; padding:5px; } <input value="Everything between {{}} is {{processed}}" /> <div></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!');

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的原型,你总是可以把它调整成独立的,或者把它放在其他的名称空间里,等等。

let age = 3;

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

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