传统的 JavaScript 语言,输出模板通常是这样写的

上面这种写法相当繁琐不方便,ES6 引入了模板字符串解决这个问题。

模板字符串(template string)是增强版的字符串,用反引号(`)标识。它可以当作普通字符串使用,也可以用来定义多行字符串,或者在字符串中嵌入变量。
对运算的支持

字符串查找
ES6还增加了字符串的查找功能,而且支持中文
查找是否存在:
先来看一下ES5的写法

网页中输出了23,我们还要自己判断
ES6直接用includes就可以判断,不再返回索引值

判断开头是否存在:
msg.startsWith(qiang)
判断结尾是否存在:
msg.endsWith(qiang)
注意:starts和ends 后边都要加s,
复制字符串
有时候是需要字符串重复的,比如分隔符和特殊符号,这时候复制字符串就派上用场了,语法很简单。
document.write(' repeat |'.repeat(3));
网友评论