es6 新增字符串方法


es6新增了4個字符串處理的方法:startsWith,endsWith,includes,repeat。

1、簡單使用

  • includes()返回布爾值,表示是否找到了參數字符串
  • startsWith()返回布爾值,表示參數字符串是否在源字符串的頭部
  • endsWith()返回布爾值,表示參數字符串是否在源字符串的尾部
 let str="lxy";
        //字符串是否以某個字符開頭
        console.log(str.startsWith('l'));//true
        console.log(str.startsWith('x'));//false
        //字符串是否以某個字符結尾
        console.log(str.endsWith('x'));//false
        console.log(str.endsWith('y'));//true
        //字符串是否包含某個字符
        console.log(str.includes('x'));//true
        console.log(str.includes('z'));//false
        //repeat()重復某個字符串幾次
        console.log(str.repeat(3));//lxylxylxy
        console.log(str.repeat(5));//lxylxylxylxylxy

2、第2個參數[update20170606]

includes(),startsWith(),endsWith()都支持第2個參數。

使用第2個參數n時,endsWith的行為與其他兩個方法有所不同。

  • endsWith針對前n個字符
  • 其他2個方法:針對從第n個位置直到字符串結束的字符。
var s="hello world!";
s.startsWith('world',6);//true
s.endsWith('hello',5);//true
s.includes('hello',6);//false

 

 

本文作者starof,因知識本身在變化,作者也在不斷學習成長,文章內容也不定時更新,為避免誤導讀者,方便追根溯源,請諸位轉載注明出處:http://www.cnblogs.com/starof/p/6919733.html有問題歡迎與我討論,共同進步。 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM