原来在用JS处理字符串的时候,经常有替换字符串模板中变量的需求,因为JS原生是不支持的,所以可以用正则表达式处理,github上也有好多开源的JS模板引擎处理这件事。ES6中直接把这个功能加进来了,方便了大家。这章的规范在11.8.6以及12.2.9,有兴趣的自己去看看。
JS中用“${}”种形式表示template中的变量,用·${}·表示模板,看个例子:
var name = "Kyle";
var greeting = `Hello ${name}!`;
console.log( greeting ); // "Hello Kyle!"
console.log( typeof greeting ); // "string"
console.log("--" + greeting + "--")//--Hello Kyle!--
还可以换行:
var text =
`Now is the time for all good men
to come to the aid of their
country!`;
console.log( text );
${}两个大括号之间可以是任何有效的表达式,还可以有函数调用,甚至在嵌入其它的`${}`,非常灵活。
function upper(s) {
return s.toUpperCase();
}
var who = "reader"
var text =
`A very ${upper( "warm" )} welcome
to all of you ${upper( `${who}s` )}!`;
console.log( text );
// A very WARM welcome
// to all of you READERS!
下面看一下两个大括号之前的变量作用域问题:
function foo(str) {
var name="foo";
console.log( str );
}
function bar() {
var name = "bar";
foo( `Hello from ${name}!` );
}
var name = "global";
bar(); // "Hello from bar!"
从上面的结果可以看出,name的值是词法作用域中的bar,而不是执行时的foo,换一种说法,变量是静态绑定的,不是动态绑定的。
ES6中还加了一种新的字符串特性,就是叫raw string,我们知道一些字符在字符串中会被转义,例如\t,\r等,如果我们不想转义就得使用两个\\表示,比较麻烦。现在ES6加入一种新的写法:
let str = String.raw`This is a text
with multiple lines.
Escapes are not interpreted,
\n is not a newline.`;
console.log(str);
/*This is a text
with multiple lines.
Escapes are not interpreted,
\n is not a newline.*/
其实这种写法在C#中早就有了,C#中用@+字符串表示非转义字符串,用来写文件路径的时候非常方便。
*以上全部代码在Firefox 43下通过测试