ES6——字符串

  • 拓展方法

    • 子串的识别

      ES6 之前判断字符串是否包含子串,用 indexOf 方法,ES6 新增了子串的识别方法

      • includes(substr)

        返回布尔值,判断是否找到参数字符串

      • startsWith(substr)

        返回布尔值,判断参数字符串是否在原字符串的头部

      • endsWith(substr)

        返回布尔值,判断参数字符是否在原字符串尾部

      以上方法都有第二个可选参数,表示搜索起始位置索引

      注意

      1. 这三个方法都只返回布尔值,如果需要知道子串的位置,还是得用 indexOf 和 lastIndexOf
      
      1. 这三个方法传入正则表达式,会抛出错误。而 indexOf 等方法,会正确理解正则表达式
  • 字符串重复

    • repeat(count)

      返回新的字符串,表示将字符串重复指定次数返回

      "hello".repeat(2)		//"hellohello"
      
  • 字符串补全

    • padStart

      返回新的字符串,表示参数字符串从头部(左侧)补全原字符

      • padEnd

        返回新的字符串,表示参数字符串从尾部(右侧)补全原字符

      
      console.log("h".padStart(5,"o"));  // "ooooh"
      console.log("h".padEnd(5,"o"));    // "hoooo"
      console.log("h".padStart(5));      // "    h",默认空格填充
      //若指定长度小于等于原字符串长度,则返回原字符串
      console.log("hello".padStart(5,"A"));  // "hello"
      
  • 模板字符串

    定义多行字符串,加入变量和表达式

    let name = "Mike";
    let age = 27;
    let info = `My Name is ${name},I am ${age+1} years old next year.`
    console.log(info);
    // My Name is Mike,I am 28 years old next year.
    

猜你喜欢

转载自www.cnblogs.com/angle-yan/p/13379829.html