学习内容:
- 字符串的unicode表示法
- 字符串的遍历器接口
- 模板字符串 (反引号``)
- String.fromCodePoint()
- String.prototype.includes()
- String.prototype.startsWith()
- String.prototype.endsWith()
- String.prototype.repeat()
上面几个方法不带prototype的方法是静态方法,有prototype是实例方法。
unicode表示法
表示一个字符的几种方法:
- z,直接写出字符串
- \u{码点} (ES6中这样使用码点)
- \HHH,八进制
- \xHH,十六进制
- \u0000~ffff (ES5中这样使用码点,且码点不能大于四个f)
字符串的遍历
let s = 'world'
for(item of s) {
console.log(item)
}
-------
w
o
r
l
d
模板字符串
ES6中对单引号和双引号不作区分。
使用反引号实现字符串的换行:
// ES5的写法
let str1 = '这是第一行\n'
+'这是第二行\n'
+'这是第三行'
console.log(str1)
// ES6的写法
let str2 = `这是第一行
这是第二行
这是第三行`
console.log(str2)
-------------------
这是第一行
这是第二行
这是第三行
这是第一行
这是第二行
这是第三行
有了反引号,输出html文本代码就很方便了。
再来看个例子:
模板字符串是的变更用${ 变量名称 }
const a = 30
const b = 70
const c = '元'
let str1 = '请计算30+70等于:' + (a + b) + c // 很容易写错
console.log(str1)
let str2 = `请计算30+70等于:${a + b}${c}` // 使用模板字符串就好很好
console.log(str2)
---------------------------
请计算30+70等于:100元
请计算30+70等于:100元
嵌套模板的例子
场景:html定义的属性不是固定的,比如class是经过逻辑运算得到的。这里举一个根据屏幕大小动态得到icon big 还是icon small的例子:
const isLargeScreen = () => {
return true
}
let class1 = 'icon'
// ES5实现方式
class1 += isLargeScreen() ? ' icon-big' : ' icon-small'
console.log(class1)
// ES6模板字符串
const class2 = `icon icon-${isLargeScreen() ? 'big' : 'small'}`
console.log(class2)
-----------------------
icon icon-big
icon icon-big
带标签的模板字符串
注意:
1、方法里传递模板字符串时,要直接传递,不需要括号
2、输出的:raw: (3) ['我是', ',我的年龄是', '岁']被称为原始字符串
const func = (a, b, c, d) => {
console.log(a)
console.log(b)
console.log(c)
console.log(d)
}
const name = 'Sure'
const age = 36
func`我是${name},我的年龄是${age}岁` // 向方法里传递模板字符串时,要直接传递,不需要括号
--------------------------------------------------
(3) ['我是', ',我的年龄是', '岁', raw: Array(3)]
0: "我是"
1: ",我的年龄是"
2: "岁"
length: 3
raw: (3) ['我是', ',我的年龄是', '岁']
Sure
36
undefined
String.fromCodePoint()
console.log(String.fromCharCode(0x20BB7)) //ES5
console.log(String.fromCodePoint(0x20BB7))
------------------------------
ஷ // ES5无法识别,因为大于ffff
𠮷 // ES6可以
String.prototype.includes()
返回是否包含某字符串,返回boolean类型
String.prototype.startsWith()、String.prototype.endsWith()
以谁开头,以谁结尾,返回boolean类型
String.prototype.repeat()
重复拼接字符串
const str = 'string '
const newStr = str.repeat(10) // 重复10次
console.log(newStr)
-------------------------------------------------------------------------
string string string string string string string string string string