一、indexOf()
1.定義
indexOf()方法返回String對象第一次出現指定字符串的索引,若未找到指定值,返回-1。(數組同一個概念)
2.語法
str.indexOf(searchValue[, fromIndex])
- searchValue:字符串對象中被查找的值。
- fromIndex:開始查找的索引,默認為0。
3.示例
let str = 'Hello, indexOf!';
console.log(str.indexOf('Hello')); // 0
console.log(str.indexOf('indexOf')); // 7
console.log(str.indexOf('l')); // 2
console.log(str.indexOf('l', 2)); // 2 加上開始查找的索引
console.log(str.indexOf('l', 3)); // 3
console.log(str.indexOf('e', 3)); // 10
console.log(str.indexOf('l', 4)); // -1
console.log(str.indexOf('world')); // -1
4.注意
區分大小寫
let str = 'Hello, indexOf!';
console.log(str.indexOf('e')); // 1
console.log(str.indexOf('E')); // -1
二、includes()
1.定義
includes()方法判斷一個字符串是否包含在另一個字符串中,返回true或false。
2.語法
str.includes(searchString[, position])
- searchString:要搜索的字符串。
- position:表示從哪個索引開始搜索,默認為0。
3.示例
let str = 'Hello, includes!';
console.log(str.includes('Hello')); // true
console.log(str.includes('includes')); // true
console.log(str.includes('hello')); // false
console.log(str.includes('Helle')); // false
console.log(str.includes('Helle', 1)); // false
console.log(str.includes('e', 2)); // true
三、startsWith()
1.定義
startsWith()方法用於判斷一個字符串是否在另一個字符串的頭部,返回true或false。
2.語法
str.startsWith(searchString[, position])
3.示例
let str = 'Hello, startsWith!';
console.log(str.startsWith('Hello')); // true
console.log(str.startsWith('H')); // true
console.log(str.startsWith('h')); // false
console.log(str.startsWith('startsWith')); // false
console.log(str.startsWith('startsWith', 7)); // true
四、endsWith()
1.定義
endsWith()方法用於判斷一個字符串是否在另一個字符串的尾部,返回true或false。
2.語法
str.endsWith(searchString[, length])
- searchString:要搜索的字符串。
- length:作為查找字符串(str)的長度,默認是字符串本身的長度。
3.示例
let str = 'Hello, endsWith!';
console.log(str.endsWith('endsWith!')); // true
console.log(str.endsWith('EndsWith!')); // false
console.log(str.endsWith('Hello')); // false
console.log(str.endsWith('end', 10)); // true