一:模板字符串
es6前字符串拼接的噩梦:
1.字符串换行
2.字符串中含有变量或者表达式
3.字符串中含有逻辑运算
es6之后改良
- 1.String Literals(解决字符串拼接噩梦1)
`string text`
`string text line 1
string text line 2`
`string text ${expression} string text`
注意:(1)在这里你可以任意插入变量或者表达式,只要用 ${} 包起来就好。
(2).这里的符号是反引号,不是单引号或者双引号。
- 2.Tag Literals(解决字符串拼接噩梦3)
function Price(strings, type) {
let s1 = strings[0]
const retailPrice = 99
const wholesalePrice = 88
let txt = ''
if (type === 'retail') {
txt = `购买单价是:${retailPrice}`
} else {
txt = `批发价是:${wholesalePrice}`
}
return `${s1}${txt}`
}
let showTxt = Price `您此次的${'retail'}`
console.log(showTxt) //您此次的购买单价是:99
二:扩展方法
- 1.String.prototype.includes()
判断一个字符串是否包含在另一个字符串中,返回boolean类型的值。
const a1 = 'includes'
console.log(a1.includes('ud')) //true
- 2.String.prototype.startsWith()
判断参数字符串是否在原字符串的头部, 返回boolean类型的值。
const a2 = 'startsWith'
console.log(a2.startsWith('sta')) //true
- 3.String.prototype.endsWith()
判断参数字符串是否在原字符串的尾部, 返回boolean类型的值。
const a3 = 'endsWith'
console.log(a3.endsWith('th')) //true
- 4.String.prototype.repeat()
返回一个新字符串,表示将原字符串重复n次。
const a4 = 'repeat-'
const aaa = a4.repeat(5)
console.log(aaa) //repeat-repeat-repeat-repeat-repeat-
- 5.String.prototype.fromCodePoint()
用于从 Unicode 码点返回对应字符,并且可以识别大于0xFFFF的字符。
console.log(String.fromCodePoint(0x21BA6)) //𡮦