The IndexOf () method is used to determine whether a string exists in a longer string. Searches from the left end of a long string to the right end, and returns where it is (that is, the index) if the substring exists. If the string being searched is not found, the string to find is returned-1. Note that the position here should fill in the index value. All string indexes are zero-based, the first character is 0, and the end position is the length of the string minus 1.
This method is equivalent to the STRSTR function in C and the InStr function in Visual Basic language. This method also has a corresponding function, namely LastIndexOf (), to search from the right end of a long string.
So the question comes, and the search () method also returns the target from the string index value. What is the difference between indexOf () and search ()? Why should you use it when you should use the search () method?
The first thing to make clear is that the parameter of search () must be a regular expression, whereas the parameter of indexof () is just a normal string. IndexOf () is a much lower-level method than search ().
If you just look for a specific string, the system resources using indexof () are less expensive and more efficient; If you are looking for a string with some characteristics (such as looking for a string that starts with a, followed by a number), then indexof () is powerless. You must use the regular expression and the search () method.
Many times using indexof () is not to really want to know the location of the substring, but rather to know that the long string does not contain this substring. If the return index value is-1, then the description does not: Not equal to 1, then there is.
So in general, indexof is more resource-saving than search.
The difference between string function indexof and search in JS