One, IndexOf () 1. Definition
The IndexOf () method returns the index of the specified string for the first occurrence of the string object, and returns 1 if the specified value is not found. (Array same concept)
2. Syntax
str.indexOf(searchValue[, fromIndex])
- Searchvalue: The value that is being looked up in the string object.
- FromIndex: The index at which to start the lookup, which defaults to 0.
3. Example
let str = 'Hello, indexOf!';console.log(str.indexOf('Hello')); // 0console.log(str.indexOf('indexOf')); // 7console.log(str.indexOf('l')); // 2console.log(str.indexOf('l', 2)); // 2 加上开始查找的索引console.log(str.indexOf('l', 3)); // 3console.log(str.indexOf('e', 3)); // 10console.log(str.indexOf('l', 4)); // -1console.log(str.indexOf('world')); // -1
4. Pay attention to case sensitivity
let str = 'Hello, indexOf!';console.log(str.indexOf('e')); // 1console.log(str.indexOf('E')); // -1
II, includes () 1. Definition
The includes () method determines whether a string is contained in another string and returns True or false.
2. Syntax
str.includes(searchString[, position])
- SearchString: The string to search for.
- Position: Indicates the index from which to start the search, the default is 0.
3. Example
let str = 'Hello, includes!';console.log(str.includes('Hello')); // trueconsole.log(str.includes('includes')); // trueconsole.log(str.includes('hello')); // falseconsole.log(str.includes('Helle')); // falseconsole.log(str.includes('Helle', 1)); // falseconsole.log(str.includes('e', 2)); // true
Iii. StartsWith () 1. Definition
The StartsWith () method is used to determine whether a string is in the header of another string and returns True or false.
2. Syntax
str.startsWith(searchString[, position])
3. Example
let str = 'Hello, startsWith!';console.log(str.startsWith('Hello')); // trueconsole.log(str.startsWith('H')); // trueconsole.log(str.startsWith('h')); // falseconsole.log(str.startsWith('startsWith')); // falseconsole.log(str.startsWith('startsWith', 7)); // true
Iv. EndsWith () 1. Definition
The EndsWith () method is used to determine whether a string is at the end of another string and returns True or false.
2. Syntax
str.endsWith(searchString[, length])
- SearchString: The string to search for.
- Length: As a lookup string (str), the default is the length of the string itself.
3. Example
let str = 'Hello, endsWith!';console.log(str.endsWith('endsWith!')); // trueconsole.log(str.endsWith('EndsWith!')); // falseconsole.log(str.endsWith('Hello')); // falseconsole.log(str.endsWith('end', 10)); // true
Four ways JavaScript determines whether a string is contained in another string