原型方法
- includes:判断是否包含某段字符
- startsWith、endsWith :判断开头和结尾是否包含某个字符
console.log(strTest.startsWith('z')) // true
console.log(strTest.endsWith('an')) // true
- repeat:重复一段字符串,参数为重复多少次
- padStart、padEnd:从前 / 后开始填充,参数:目标长度、填充内容(不传即为空格填充)
const str = 'zs'
console.log(str.padStart(5, 'hi-')) // hi-zs
console.log(str.padEnd(5, '-hi')) // zs-his
- trim :去掉字符串前后所有空格
- trimStart : 去掉开始空格、trimLeft 已废弃
- trimEnd :去掉结尾空格;trimRight 已废弃
字符串扩展
- 支持 Unicode:\u(表示unicode) + 码点(0000~ffff)
const a = `\u{20BB7}` // 吉
const b = `\u{41}` // A
const c = `\u{7A}` // z
- 码点转换
- fromCharCode(es5 不能大于 ffff)
- fromCodePoint(es6)
console.log(String.fromCharCode(0x41)) // A
console.log(String.fromCodePoint(0x20bb7)) // 吉
- 进制转换
const a = 5
console.log(a.toString(2)) // 转换二进制 101
const c = 0b101 // 0B 二进制
console.log(c) // 5
const d = 0o777 // 0o 八进制
console.log(d) // 511
- 模板字符串、嵌套模板 ${}
const str = `
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
`
const isLargeScreen = () => true
const classNames = `icon icon-${isLargeScreen() ? 'big' : 'small'}` // 嵌套模板
- 放松模板字符串 :不识别会定性为 undefined、ES9 之前会发生报错
// \u{61} 代表 a \u{62} 代表 b
const x = `\u{61} and \u{62}` // 'a and b'
标签模板字符串
const foo = (a, b, c) => {
console.log(a) // ['名字', ',年龄', '岁', raw: Array(3)]
console.log(b) // zhangsan
console.log(c) // 18
}
const name = 'zhangsan'
const age = 18
foo`名字${name},年龄${age}岁`