考虑下面的代码:

var age = 3;

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

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


当前回答

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

你可以这样做

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

or

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

其他回答

自定义灵活插补:

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>

let age = 3;

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

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

从ES6开始,你可以使用模板文字:

Const age = 3 console.log(' I'm ${age} years old! ')

附注:注意反引号的使用:' '。

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

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

你可以很容易地使用ES6模板字符串,并使用任何可用的transpilar(如babel)编译到ES5。

const age = 3;

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

http://www.es6fiddle.net/im3c3euc/