<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>es6字符串新增特性</title>
</head>
<body>
<script>
//unicode 表示方法
{
console.log('a', '\u0061');
//a a
console.log('\u20bb7');
//unreadalbe code
//原因是超过了0xFFFF,当成了两个字符
console.log('\u{20bb7}');
//吉
}
//api codePointAt()
{
let s = '?a';
console.log(s.length);//3
console.log(s.charAt(0));//unreadable code
console.log(s.charCodeAt(0));//55362
console.log(s.charCodeAt(1));//57271
console.log(s.codePointAt(0));//134071
//取0时,处理的是完整的,一次处理4个字节
console.log(s.codePointAt(0).toString(16));//20bb7
console.log(s.codePointAt(1));//57271
//取1的时候,取了字符的后两个字节, 和charCodeAt一样
console.log(s.codePointAt(2));//97
}
//api fromCodePoint
{
console.log(String.fromCharCode('0x20bb7'));//unreadable code
console.log(String.fromCodePoint('0x20bb7'));//?
}
//字符串遍历
{
let str = '\u{20bb7}abc';
for (const code of str) {
console.log(code);
}
//这种方式不会出现乱码,对汉字的处理很好
for(let i = 0; i < str.length;i++) {
console.log(str[i]);
}
//上面这种方式会出现乱码
}
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>es6字符串新增特性</title>
</head>
<body>
<script>
//判断字符串中是否包含某个字符
{
let str = 'string';
console.log(str.includes('r'));//true
console.log(str.includes('c'));//false
}
//判断字符串是否以某些字符起始
//判断字符串是否以某些字符结束
{
let str = 'string';
console.log(str.startsWith('str'));//true
console.log(str.endsWith('ng'));//true
}
//重复
{
let str = 'abc';
console.log(str.repeat(3));//abcabcabc
}
//模版字符串
{
let info = 'world';
let m = `hello ${ info }`
console.log(m);//hello world
}
//补白
//可应用于日期中
{
console.log('1'.padStart(2, '0'));//01
console.log('1'.padEnd(2, '0'));//10
}
//标签模版
//可用于过滤html字符串,防止xss攻击
//可用于处理多国语言转换
{
let user = {
name: 'list',
info: 'hello world'
}
function abc(s, v1, v2) {
console.log(s, v1, v2);
return s+v1+v2;
}
abc`i am ${ user.name }, ${ user.info }`
console.log(abc`i am ${ user.name }, ${ user.info }`);
}
//raw保证转义\不生效
{
console.log(String.raw`hi\nworld`);//hi\nworld
console.log(`hi\nworld`);
//hi
//world
}
</script>
</body>
</html>