es5中我們經常使用indexof()方法來判斷一個字符串是否包含另外一個字符串中。
如果存在則返回匹配到的第一個索引值。如果沒有則返回 -1。所以,判斷一個字符串是否包含另外一個字符串中只需要判斷是否為-1就行。-1代表不存在。
例如:
let str = 'Hello World!'; console.log(str.indexOf('H'));//0 str中"H"的出現的第一個索引為0 console.log(str.indexOf('o'));//4 str中"o"第一個出現的位置的索引為4 console.log(str.indexOf('a'));//-1 沒找到,返回-1
雖然Es5中該方法經常使用,但是Es6提供了更加便捷的方法。
1. str.includes('');
有返回true,沒有返回false。也不用為記住-1而發愁了!!
let str = 'Hello World!'; console.log(str.includes('H'));//true console.log(str.includes('a'));//false
2.startsWith()
判斷該字符串是否為某個字符串的首位。有就是true,不是就是false。
let str = 'Hello World!'; console.log(str.startsWith('H'));//true console.log(str.startsWith('Hello'));//true console.log(str.startsWith('e'));//false
3.endsWith()
和startsWith()相反。判斷是否為末尾。
let str = 'Hello World!'; console.log(str.endsWith('!'));//true console.log(str.endsWith('d!'));//true console.log(str.endsWith('e'));//false
這三個方法都支持第二個參數,表示看是搜索的位置。
let str = 'Hello World!'; console.log(str.includes('World',5));//true 從索引5(包含索引5)開始搜索 console.log(str.includes('World',7));//false console.log(str.startsWith('lo',3))//true console.log(str.startsWith('H',3));//false console.log(str.endsWith('el',3));//true endsWith()和上面兩個不一樣,它的第二個參數代表前幾個。“Hel”,所以返回true