模板字符串
模板字符串是ES6提出的,早在ES6之前,拼接字符串是相当麻烦的
var name = 'zhangsan'
var age = 30
var info = '我的名字叫'+ name + ',年龄是'+ age
// info
// '我的名字叫zhangsan,年龄是30'
这仅仅是比较简单的拼接,如果变量增加,难度也会随之增加;但是随着模板字符串的出现,不仅仅降低了字符串的拼接难度,同时代码阅读质量也变高了(语法是:${})
- 在模板字符串中,空格、缩进、换行都会被保留
- 模板字符串完全支持“运算”式的表达式,可以在${}里完成一些计算
根据第一点,我们能轻松的拼接出html结构
let list = `
<ul>
<li>列表1</li>
<li>列表2</li>
</ul>
`
console.log(list)
除此之外,ES6还新增了一些比较好用关于字符串的方法
(1)判断是否存在,在之前,判断一个字符是否存在于字符串中,只能用indexOf > -1
来实现。现在ES6提供了三个方法:includes
、startsWith
、endsWith
,它们都返回一个布尔值告诉你是否存在
- includes: 判断某个字符是否存在于字符串中
const a = 'hehe'
const b = 'ee hehe haha'
b.includes(a)
- startsWith:判断某个字符是否存在于字符串的开头
const a = 'xixi haha hehe'
a.startsWith('haha') // false
a.startsWith('xixi') // true
- endsWith:判断某个字符是否存在于字符串的结尾
const a = 'xixi haha hehe'
a.endsWith('hehe') // true
a.endsWith('xixi') // false
(2)自动重复:可以使用 repeat 方法来使同一个字符串输出多次(被连续复制多次):
"abc".repeat(-1) // RangeError: repeat count must be positive and less than inifinity
"abc".repeat(0) // ""
"abc".repeat(1) // "abc"
"abc".repeat(2) // "abcabc"
"abc".repeat(3.5) // "abcabcabc" 参数 count 将会被自动转换成整数。
"abc".repeat(1/0) // RangeError: repeat count must be positive and less than inifinity
开发中需要用上字符串的其它方法,MDN