The indexOf() method returns the position of the first occurrence of specified character(s) in a string. Tip: Use the lastIndexOf method to return the position of the last occurrence of specified character(s) in a string.
JavaScript String indexOf() The indexOf() method returns the position of the first occurrence of a value in a string. The indexOf() method returns -1 if the value is not found. The indexOf() method is case sensitive.
The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.
The IndexOf method returns the location of the first character of the first occurrence of the substring. The index is 0-based, which means the first character of a string has an index of 0. If IndexOf does not find the substring, it returns -1.
If you require a regular expression, use search()
. Otherwise, indexOf()
is going to be faster.
indexOf
is for plain substrings, search
is for regular expressions.
The search function (one description here) takes a regular expression, which allows you to match against more sophisticated patters, case-insensitive strings, etc., while indexOf (one description here) simply matches a literal string. However, indexOf also allows you to specify a beginning index.
indexOf() and search()
common in both
i) return the first occurrence of searched value
ii) return -1 if no match found
let str='Book is booked for delivery'
str.indexOf('b') // returns position 8
str.search('b') // returns position 8
special in indexOf()
i) you can give starting search position as a second argument
str.indexOf('k') // 3
str.indexOf('k',4) // 11 (it start search from 4th position)
search value can be regular expression
str.search('book') // 8
str.search(/book/i) // 0 ( /i =case-insensitive (Book == book)
reference
I think the main difference is that search accept regular expressions.
Check this reference:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With