The difference between string function indexof and search in JS

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.