ES6(四)字符串的扩展

1、字符的表示方式

  最早在  u0000-uFFFF 之间的字符已经足够使用吗,每个字符占两个字节,超出范围,必须使用双字节形式表达,

  即每个字符占四个字节。超出范围的字符,会被解读成  uXXXX+last。

  ES6中,将码点放入 大括号中,既可以正确解读该字符。

  "hellu{6F}"

'z'
'172' 
'x7A'
'u007A'
'u{7A}'

2、

   一般来说,字符以 UTF-16 格式存储,每个字符固定为2字节。

   超过 0XFFFF范围的字符,将会出现异常。

charAt      

At

charCodeAt    codePointAt fromCharCode String.fromPointCode

无法读取整个字符 

可以识别Unicode编号大于0xFFFF的字符

只能分别返回前两个字节和后两个字节 

正确返回32位UTF-16字符码,返回的码点是十进制,使用 s.charCodeAt(2).toString(16)可以查看十六进制码点

不能识别32位的UTF-16字符  String.fromCodePoint(0x20BB7)

    String.fromCodePoint(0x1f680);

3、字符串的 for...of

  字符串类似于字符数组,因此,可以使用for...of 遍历字符串。

  可以识别 大于 0XFFFF的码点,输出的是值,而不是 索引。

     let text = '中国人民大学';
        for (let item of text) {
            console.log(item);
        }

4、字符串的 包含判断 includes、startWidth、endWidth

   /*
         * 是否包含字符串相关 函数
         * 1、includes() String.prototype.includes = function(searchString,position) {}
         * 2、startWith()  String.prototype.startsWith = function(searchString,position) {}
         * 3、endWidth() String.prototype.includes = function(searchString,position) {}
         *
         * 均支持第二个参数,表示搜索的开始位置,
     * endsWith表示第n个字符,是否有这个字符串或字符串,others第n个位置直到字符串结束之间是否有这个字符串。 *
*/ let source = 'jack is a good boy'; source.startsWith('j'); //true source.endsWith('t', 5); //false
     source.startsWith('a',1); //true

5、字符串的自我复制 repeat()

 String.prototype.repeat = function(count) {}

'na'.repeat(3);


6、模板字符串
  (1)模板字符串 template string,用反引号` 标识,可以用来定义多行字符串,或者在字符串中嵌入变量
      如果使用模板字符串表示多行字符串,所有空格和缩进都会被保留在输出之中,如果不需要,可用 ''.trim()除去
       let x = 1, y = 2;

        `${x}+${y}=${x+y}`;

     (2)模板字符串还能调用函数

 const data=[
            { first:'jack',last:'Bond'},
            { first:'Tom' , last:'li'}
        ];

        const tmpl=addrs=>`
            <table>
                ${addrs.map(addr=>`
                    <tr><td>${addr.first}</td></tr>
                    <tr><td>${addr.last}</td></tr>
                `
                ).join('')}
            </table>
        `;//使用 join 避免多行之间 多余 逗号

        console.log(tmpl(data));

   (3)如果需要引用模板字符串本身,应如下

 let helloName='name=>`hello ${name}`',
    getName=eval.call(null,helloName);
 getName('jack');

    (4)

      String.raw 往往用来充当模板字符串的处理函数,返回一个斜杠被转移的字符串,对应于替换后的模板字符串

    作为正常函数使用,它的一个参数,应该是具有raw属性的对象
   String.raw = function(template,substitutions) {}      
 String.rawExample = function (strings, ...values) {
            var output = "";
            for (var index = 0; index < values.length; index++) {
                output += strings.raw[index] + values[index];
            }

            output += strings.raw[index]
            return output;
        }

7、标签模板

 标签模板不是模板,而是函数调用的一种特殊形式,标签指 函数,模板是 参数
     alert`123`;
        let a= 5,b=10;
        function tag(stringArr,...args){
            console.log(stringArr);
        }

        tag`hello${a+b} world ${a*b}`;





原文地址:https://www.cnblogs.com/xianrongbin/p/6867881.html