indexOf() method returns the index of the first occurrence of a value in a string.
syntax ↴
indexOf(searchString, start) ↴
searchString Substring to search for. All values are coerced to strings.
start (optional). The start position within the string at which to begin searching for searchString. Defaults to 0.
indexOf() method returns -1 if the value is not found.
indexOf() method is case sensitive.
String to be searched for (searchString) must be a string and cannot be a regex.
If string to be searched for is a regex then indexOf() method returns -1
You can use a start index (position) where the searchString is expected to start from. Default start position is 0.
If start index (position) is less than zero, the method behaves as if start position were 0.
When checking if a specific substring occurs within a string, the correct way to check is test whether the return value is -1 ↴
'Blue Whale'.indexOf('Blue') !== -1; // true; found 'Blue' in 'Blue Whale'
'Blue Whale'.indexOf('Bloe') !== -1; // false; no 'Bloe' in 'Blue Whale'
indexOf() and search() methods are similar, except ↴
indexOf() method cannot search against a regular expression.
search() method can search against a regular expression but cannot take a start position argument.
myString.indexOf(searchString)
myString.indexOf(searchString, start)