1. 程式人生 > 實用技巧 >ES6——字串

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.