es6字符串新增特性

<!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>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值