ES6字符串包含方法


5.3.3 String

5.字符串包含方法

ECMAScript6增加了3個用於判斷字符串是否包含另一個字符串的方法:startsWith()、endsWith()和includes()。

let message = "foobarbaz";
console.log(message.startsWith("foo")); // true
console.log(message.startsWith("bar")); // false
console.log(message.endsWith("baz")); // true
console.log(message.endsWith("bar")); // false
console.log(message.includes("bar")); // true
console.log(message.includes("qux")); // false

startsWith() 和 includes() 方法接收可選的第二個參數,表示
開始搜索的位置。如果傳入第二個參數,則意味着這兩個方法會從指定
位置向着字符串末尾搜索,忽略該位置之前的所有字符。下面是一個例
子:

let message = "foobarbaz";
console.log(message.startsWith("foo")); //true
console.log(message.startsWith("foo", 1)); //false
console.log(message.includes("bar")); //true
console.log(message.includes("bar", 4)); //false
console.log(message.startsWith("bar", 3));// true

endsWith() 方法接收可選的第二個參數,表示應該當作字符串末尾
的位置。如果不提供這個參數,那么默認就是字符串長度。如果提供這
個參數,那么就好像字符串只有那么多字符一樣:

let message = "foobarbaz";
console.log(message.endsWith("bar")); //false
console.log(message.endsWith("bar", 6)); // true

 

另注意:對象數組不能使用includes進行檢測


免責聲明!

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



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