ES6新增API:String篇(一)

226 阅读2分钟

这是我参与11月更文挑战的第7天,活动详情查看:11月更文挑战

  1. String.raw

    String.raw是一个模板字符串的标签函数(如果你不知道什么是标签函数,点⚑),它返回模板字符串的原始字符串。比如说\n不会被当成换行处理,而是被当做两个普通字符``和n

    console.log(String.raw`1\n2`); //1\n2
    

    通常,我们不需要把它当做普通函数来调用,但是如果你一定要把它当做普通函数调用的话,要注意传入参数的格式:

    (template: {
        raw: readonly string[] | ArrayLike<string>;
    }, ...substitutions: any[])=>string
    

    String.raw的第一个参数必须是一个有raw属性的对象,该属性值为字符数组或者字符类数组,剩余参数就是插入的值。

    console.log(String.raw({ raw: 'abcd' }, 0, 1, 2)); //a0b1c2d
    //3 4两个插值超出了模板数组的范围,会被忽略
    console.log(String.raw({ raw: ['a', 'b', 'c', 'd'] }, 0, 1, 2, 3, 4)); //a0b1c2d
    
  2. String.prototype.repeat

    函数类型:

    (count?:number)=>string
    

    repeat函数会根据传入的参数n,返回一个原字符串重复了n次的新字符串,参数n默认为0

    //传入0或者不传参数时,原字符串重复0次,返回空字符串
    console.log('a'.repeat(0));// ''
    console.log('a'.repeat(2));// 'aa'
    
  3. String.prototype.startsWith,String.prototype.endsWith,String.prototype.includes

    函数类型:

    (queryString?:string,startPosition?:number)=>boolean
    

    startsWithendsWidthincludes函数都是ES6新增的用于检查字符串的函数,它们接收两个参数,第一个参数queryString是要在原字符串中查询的字符串,第二个参数startPostion是开始查询的位置。在includesstartsWith中,startPosition默认值为0,在endsWith中,startPostion默认为原字符串length

    console.log('abcde'.includes('a')); //true
    //改变起始位置
    console.log('abcde'.includes('a', 1)); //false
    console.log('abcde'.startsWith('a')); //true
    //改变起始位置
    console.log('abcde'.startsWith('a', 1)); //false
    ​
    console.log('abcde'.endsWith('a')); //false
    //改变起始位置
    console.log('abcde'.endsWith('a', 1)); //true
    

    要注意的是,当要检查的字符串,即参数queryString空字符串''时,这三个函数的返回结果始终为true

    console.log('abcde'.includes('')); //true
    //改变起始位置
    console.log('abcde'.includes('', 1)); //true
    console.log('abcde'.startsWith('')); //true
    //改变起始位置
    console.log('abcde'.startsWith('', 1)); //true
    console.log('abcde'.endsWith('')); //true
    //改变起始位置
    console.log('abcde'.endsWith('', 1)); //true