zoukankan      html  css  js  c++  java
  • 字符串的扩展

    概述

    ES6增加了对字符串的扩展。

    1.字符串的遍历器接口

    ES6为字符串添加了遍历器接口,使得字符串可以被for...of循环遍历。

    for (let codePoint of 'foo') {
      console.log(codePoint)
    }
    // "f"
    // "o"
    // "o"
    

    2.includes(), startsWith(), endsWith()

    • includes():返回布尔值,表示是否找到了参数字符串。
    • startsWith():返回布尔值,表示参数字符串是否在原字符串的头部。
    • endsWith():返回布尔值,表示参数字符串是否在原字符串的尾部。
    var s = 'Hello world!';
    
    s.startsWith('Hello') // true
    s.endsWith('!') // true
    s.includes('o') // true
    

    这三个方法支持第二个参数,表示开始搜索的位置。

    var s = 'Hello world!';
    
    s.startsWith('world', 6) // true
    s.endsWith('Hello', 5) // true
    s.includes('Hello', 6) // false
    

    使用第二个参数n时,endsWith的行为与其他两个方法有所不同。它针对前n个字符,而其他两个方法针对从第n个位置直到字符串结束。

    3.repeat()

    'x'.repeat(3) // "xxx"
    'hello'.repeat(2) // "hellohello"
    'na'.repeat(0) // ""
    
    参数如果是小数,会被取整。
    'na'.repeat(2.9) // "nana"
    
    如果repeat的参数是负数或者Infinity,会报错。
    'na'.repeat(Infinity)
    // RangeError
    'na'.repeat(-1)
    // RangeError
    
    
    如果参数是0到-1之间的小数,则等同于0,这是因为会先进行取整运算。0到-1之间的小数,取整以后等于-0,repeat视同为0。
    'na'.repeat(-0.9) // ""
    
    参数NaN等同于0
    'na'.repeat(NaN) // ""
    
    如果repeat的参数是字符串,则会先转换成数字。
    'na'.repeat('na') // ""
    'na'.repeat('3') // "nanana".

    4.padStart(),padEnd()

    ES2017 引入了字符串补全长度的功能。如果某个字符串不够指定长度,会在头部或尾部补全。padStart()用于头部补全,padEnd()用于尾部补全。

    'x'.padStart(5, 'ab') // 'ababx'
    'x'.padStart(4, 'ab') // 'abax'
    
    'x'.padEnd(5, 'ab') // 'xabab'
    'x'.padEnd(4, 'ab') // 'xaba'
    
    //padStart和padEnd一共接受两个参数,第一个参数用来指定字符串的最小长度,第二个参数是用来补全的字符串。
    
    'xxx'.padStart(2, 'ab') // 'xxx'
    'xxx'.padEnd(2, 'ab') // 'xxx'
    
    //如果用来补全的字符串与原字符串,两者的长度之和超过了指定的最小长度,则会截去超出位数的补全字符串。
    
    'abc'.padStart(10, '0123456789')
    // '0123456abc'

    //如果省略第二个参数,默认使用空格补全长度。
    'x'.padStart(4) // '   x'
    'x'.padEnd(4) // 'x   '

    5.模板字符串

    ES6中引入了模板字符串(Template Literal),是创建字符串的一种新方法。有了这个新特性,我们就能更好地控制动态字符串。这将告别长串连接字符串的日子。

    1.多行字符串

    let myStr = `hello
    world`;
    console.log(myStr)   //hello
                         //world
    

    2.表达式

    let nameVal = 'xiaoli';
    let str = `my name is ${nameVal}`
    console.log(str)   //my name is xiaoli

    相关链接

    1.ES6简介

    2.let和const命令

    3.变量的解构赋值

    参考资料

    1.阮一峰的《ES6入门》

  • 相关阅读:
    ✨Synchronized底层实现---偏向锁
    🌞LCP 13. 寻宝
    ✨Synchronized底层实现---概述
    ⛅104. 二叉树的最大深度
    c++多线程之顺序调用类成员函数
    C++ STL实现总结
    C#小知识
    C#中HashTable和Dictionary的区别
    WPF的静态资源(StaticResource)和动态资源(DynamicResource)
    WPF之再谈MVVM
  • 原文地址:https://www.cnblogs.com/helloluo/p/7498598.html
Copyright © 2011-2022 走看看