ECMAScript6--5.字符串扩展

2017-10-18  本文已影响25人  飞菲fly

1.字符串新增特性

3.formCharCode--根据码值给出对应的字符

    {
        //ES5和ES6最大的区别就是能不能处理unicode字符
        (大于0xFFFF--大于两个字节的unicode字符);
        
        //ES5:
        console.log(String.formCharCode("0x20bb7")); //乱码
   
        //ES6:
        console.log(String.fromCodePoint("0x20bb7")); //吉
   
    }

4.字符串遍历器接口:let of 遍历器

通过字符串的遍历器接口可以正常处理字符串中包含unicode编码大于0xFFFF的情况;

    {
        let str ='\u{20bb7}abc';
        
        //ES5:遍历
        for(let i=0;i<str.length;i++){
            console.log('ES5',str[i]); //乱码 乱码 a b c
        }
        
        //ES6:
        for(let code of str){
            console.log('ES6:',code); //吉 a b c
        }
    }

5.includes && startsWith && endsWith

1.includes:判断字符串中是否包含某些字符
2.startsWith &&endswith:判断一个字符串是不是以某些字符为起始或截止

   {
    //判断字符串中是否包含某些字符
    //判断字符串中是不是包含r字符
    let str ="string";
    console.log('includes:',str.includes("r")); // includes true
    
    //一个字符串是不是以某些字符为起始或截止
    //判断是不是以str开始的
    console.log('start',str.startsWith('str')); //start true
    
    //判断是不是以ng截止的
    console.log('end',str.endsWith('ng')); //end  true
    }
    
    {
        //重复--字符串的复制功能
        let str = 'abc';
        
        //ES6:repeat(数字)  数字:指定重复的次数
        console.log(str.repeat(2)); //abcabc
    }

6.模板字符串--把数据和模板最后拼成一个带结果的字符串

    {
        let name ="list";
        let info = "Hello world!"
        
        let m =`i am ${name},${info}`;//(`键盘数字1左边的按键)
        console.log(m); //i am list,hello world!
    }

7.padStart && padEnd

ES6没有实现,ES7的一个草案,加了babel--polyfill这个库的话也是可以在ES6中使用的;
padStart:补白的作用--向前补;
padEnd: 补白的作用--向后补;

    {
        //padStart 补白的作用--向前补;(例如:日期小于10的01-09可以用这个)
            API返回的最终结果就是要求第一个参数是长度
           (api返回的字符串必须满足第一个参数指定的长度),如果长度不够第二个参数要补什么
        console.log('1'.padStart(2,'0')); //01
        
        //padEnd 向后补白;
        console.log('1'.padEnd(2,'0')); //10
        
    }

8.标签模板

作用:
1.在过滤html字符串的时候(在防止xss攻击的时候用这个处理)
2.处理多语言转换的时候;

{
 let user ={
      name:'list',
      info:'hello world'
  };
        
 console.log(abc`i am ${user.name},${user.info}`);//输出:i am ,,,listhello world
 function abc(s,v1,v2){
      //["i am",",","",raw:Array[3]] "list" "hello world"
      console.log(s,v1,v2); 
      return s+v1+v2;
   }
    
 }

9.raw

raw对所有的斜杠进行了转义,斜杠之前加了斜杠,斜杠是不生效的;

    {  
        console.log(string.raw'Hi\n${1+2}'); //Hi\n3(\n换行符并没有生效)
        console.log('Hi\n${1+2}'); // Hi   3
    }
上一篇 下一篇

猜你喜欢

热点阅读