美文网首页前端开发笔记让前端飞
ECMAScript6面对大于0xFFFF的Unicode字符如

ECMAScript6面对大于0xFFFF的Unicode字符如

作者: 后除 | 来源:发表于2018-02-05 15:12 被阅读11次

    一、match()

    1.定义

    match()方法用于检索字符串内指定(字符串或正则)的值,返回指定值的数组,若找不到,返回null。

    2.语法

    str.match(searchvalue)
    str.match(regexp)
    

    3.示例

    let str = 'abc-def-zxc';
    console.log(str.match('-')); // ["-", index: 3, input: "abc-def-zxc"]
    console.log(str.match(/[a-z]{3}/g)); // ["abc", "def", "zxc"]
    

    4.注意

    match()常常与正则标识g配合使用,若没有g则只匹配一次。

    let str = 'abc-def-zxc';
    console.log(str.match(/[a-z]{3}/)); // ["abc", index: 0, input: "abc-def-zxc"]
    console.log(str.match(/[a-z]{3}/g)); // ["abc", "def", "zxc"]
    

    二、使用match()方法判断大于0xFFFF的Unicode字符长度

    正则标识u能识别码点大于0xFFFF的Unicode字符。

    console.log(/^.$/.test('𠮷')); // false 正常情况下𠮷被当作两个字符
    console.log(/^.$/u.test('𠮷')); // true
    

    利用u这个特性可以用来验证判断大于0xFFFF的Unicode字符长度。

    function getRealLength (str) {
        let ret = str.match(/./gu);
        return ret ? ret.length : 0;
    }
    let str = '𠮷𠮷𠮷';
    console.log(str.length); // 6
    console.log(getRealLength(str)); // 3
    

    三、扩展运算符/2018-02-13

    扩展运算符可以将字符串转成真正的数组,并且能够识别四个字节的Unicode字符。因此可以利用这个特性返回字符串的真实长度。

    let str = '𠮷𠮷𠮷';
    console.log(str.length); // 6
    console.log([...str].length); // 3
    

    四、Array.from()

    1.定义

    Array.from()方法从一个类数组对象或可迭代对象中创建一个新的数组。

    2.语法

    Array.from(arrayLike, mapFn, thisArg)
    
    • arrayLike:类数组对象或可迭代对象。
    • mapFn:回调函数,新数组中每个值执行。
    • thisArg:mapFn的this对象。

    3.示例

    将字符串转换成数组,然后计算出真实的长度。

    let str = '𠮷𠮷𠮷';
    console.log(str.length); // 6
    console.log(Array.from(str).length); // 3
    

    相关文章

      网友评论

        本文标题:ECMAScript6面对大于0xFFFF的Unicode字符如

        本文链接:https://www.haomeiwen.com/subject/crxizxtx.html