字符串的Unicode表示法
image.png
//es6 unicode \uxxxx 码点0000~ffff
// \u20BB7 超出码点范围会被解析成 -> \u20BB+7
// \u{20BB7} 使用大括号后扩大码点范围
//z
console.log('\z' === 'z'); //true
// \HHH 如果\后面是八进制三位数,对应的是字符
console.log('\172' === 'z'); //true
// \xHH 如果\后面是x加两个十六进制两位数,对应的也是字符
console.log('\x7A' === 'z'); //true
// \uxxxx
console.log('\u007A' === 'z'); //true
//大括号
console.log('\u{7A}' === 'z'); //true
字符串的遍历器接口
// 字符串可遍历
for(let item of 'item'){
console.log(item); // i t e m
}
模板字符串`
- 长字符串换行
//原先的换行方式
const str1='啦啦啦啦啦\n'+
'啊啊啊啊啊啊啊啊啊\n'+
'哈哈哈哈哈哈哈哈哈'
console.log(str1);
//使用模板字符串`
const str2=`啦啦啦啦啦
啊啊啊啊啊啊啊啊啊
哈哈哈哈哈哈哈哈哈`
console.log(str2);
//使用模板字符串`
const str3=`
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<ul>`
console.log(str3);
- 变量拼接
const a=10
const b=8
const c='es'
const str4='我的年龄是'+(a+b)+',我在学'+c
console.log(str4);
//模板字符串`里的变量使用${}
const str5=`我的年龄是${a+b},我在学${c}`
console.log(str5);
- 嵌套模板
const isLargeScreen=()=>{
return true
}
let class1='icon'
class1+=isLargeScreen() ? ' icon-big' : ' icon-small'
console.log(class1); //icon icon-big
//使用模板字符串
const class2=`icon icon-${isLargeScreen()?'big':'small'}`
console.log(class2); //icon icon-big
- 带标签的模板字符串
const foo=(a,b,c,d)=>{
console.log(a);
console.log(b);
console.log(c);
console.log(d);
}
foo(1,2,3,4) //1 2 3 4
const name='daji'
const age=18
foo`这是${name},他的年龄是${age}岁` //无括号
//a=>["这是","他的年龄是","岁",raw:["这是","他的年龄是","岁"]] //raw原始字符串
//b=>daji
//c=>18
//d=>undefined 没有第三个变量
静态方法 String.fromCodePoint()
//可以把码点转化成对应的字符 在unicode中用到 使用频率不是很高
console.log(String.fromCharCode(0x20BB7));//ES5 打印出奇怪的符号
console.log(String.fromCodePoint(0x20BB7));//ES6 打印出字
实例方法 String.prototype.includes()
const str='str'
console.log(str.indexOf('r')); //indexOf存在返回下标2,不存在返回-1
console.log(str.includes('r')); //true 检查字符串内是否包含值,返回布尔值
实例方法 String.prototype.startsWith()
const str='str'
console.log(str.startsWith('s')); //true 是否以此开始,返回布尔值
实例方法 String.prototype.endsWith()
const str='str'
console.log(str.endsWith('r')); //true 是否以此结束,返回布尔值
实例方法 String.prototype.repeat()
const str='str'
const newstr=str.repeat(10) //str重复10次
console.log(newstr); //strstrstrstrstrstrstrstrstrstr