Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between indexOf() and search()?

People also ask

What is the use of indexOf ()?

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.

What is the use of indexOf () method of string object in JavaScript?

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.

Why is indexOf returning?

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.

What does indexOf do in Visual Basic?

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) 
    

  • special in search()

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:

  • search
  • indexOf