ECMAScript6之模板字符串

Template String

首先我们来回忆一下ES3,ES5中是怎么拼接字符串的:

1
2
3
var myString = "A long time ago, in a galaxy far,"+
"far away...\n"+
"It is a period of civil war.";

这种写法显然很不方便。还好ES6引入了模板字符串。

1
2
const myString = `A long time ago, in a galaxy far,far away...
It is a period of civil war.`;

在使用模板字符串表示多行字符串时,所有的空格和缩进都会保留在输出中。

现在,作为JavaScript开发者,我们有3种方法定义字符串:

  • with ""
  • with ''
  • with
    1
    2
    我们还可以使用一个模板字符串替换带有变量值的占位符,就像C/C++使用printf那样。

var items = [];
items.push(“banana”);
items.push(“tomato”);
items.push(“light saber”);
var total = 100.5;
var result = You have ${items.length} item(s) in your basket for a total of $${total};

1
2
3
4
这段代码会输出如下内容:
`You have 3 item(s) in your basket for a total of $100.5`
## Going Further with Tags
模板字符串还可以紧跟在一个函数名后面,该函数将被调用来处理这个模板字符串,这被称为标签模板。

var myUselessFunction = function(strings, …values) {
var output = ‘’;
for(var index = 0; index < values.length; index ++) {
output += strings[index] + values[index];
}
output += strings[index];
return output;
}
var result = myUselessFunctionYou have ${items.length} item(s) in your basket for a total of $${total};

1
2
3
结果与上面一样。
## String.raw
如果我们想获取未转义的字符串时,我们可以用这个方法,比如:

var myRawFunction = function (strings,…values) {
var output = “”;
for (var index = 0; index < values.length; index++) {
output += strings.raw[index] + values[index];
}
output += strings.raw[index]
return output;
}
myRawFunction You have ${items.length} item(s) in your basket\n.For a total of $${total}
等价于String.raw You have ${items.length} item(s) in your basket\n.For a total of $${total}

String.rawHi \n${2+3}
//Hi \n5
```

Conclusion

浏览器兼容性:Chrome(41+), Opera(28+) and Firefox (35+),可以从这个表中查看:
http://kangax.github.io/compat-table/es6/?WT.mc_id=13390-DEV-sitepoint-article14