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進行檢測