考虑下面的代码:
var age = 3;
console.log("I'm " + age + " years old!");
除了字符串连接之外,还有其他方法可以将变量的值插入到字符串中吗?
考虑下面的代码:
var age = 3;
console.log("I'm " + age + " years old!");
除了字符串连接之外,还有其他方法可以将变量的值插入到字符串中吗?
当前回答
博士tl;
使用ECMAScript 2015的模板字符串字面量,如果适用。
解释
根据ECMAScript 5规范,没有直接的方法来做到这一点,但ECMAScript 6有模板字符串,在规范起草期间也被称为准字面量。像这样使用它们:
> var n = 42;
undefined
> `foo${n}bar`
'foo42bar'
可以在{}中使用任何有效的JavaScript表达式。例如:
> `foo${{name: 'Google'}.name}bar`
'fooGooglebar'
> `foo${1 + 3}bar`
'foo4bar'
另一件重要的事情是,你不必再担心多行字符串了。你可以简单地写成
> `foo
... bar`
'foo\n bar'
注意:我使用io.js v2.4.0计算上面所示的所有模板字符串。你也可以使用最新的Chrome来测试上面显示的例子。
注:ES6规范现在已经最终确定,但还没有被所有主要浏览器实现。根据Mozilla开发者网络页面,这将从以下版本开始实现基本支持:Firefox 34, Chrome 41, Internet Explorer 12。如果您是Opera、Safari或Internet Explorer用户,并且现在对此感到好奇,那么可以使用这个测试平台进行测试,直到每个人都得到支持为止。
其他回答
扩展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
替换更多的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."
自定义灵活插补:
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>
我可以给你们举个例子:
函数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'));