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

后端 未结 8 1967
情歌与酒
情歌与酒 2020-12-04 07:11

Being fairly new to JavaScript, I\'m unable to discern when to use each of these.

Can anyone help clarify this for me?

相关标签:
8条回答
  • 2020-12-04 07:25

    indexOf is for plain substrings, search is for regular expressions.

    0 讨论(0)
  • 2020-12-04 07:25

    I think the main difference is that search accept regular expressions.

    Check this reference:

    • search
    • indexOf
    0 讨论(0)
  • 2020-12-04 07:33

    Search finds it's matches with a regular expression, but has no offsets. IndexOf uses literals to match, but has an offset.

    IndexOf

    Search

    0 讨论(0)
  • 2020-12-04 07:37

    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

    0 讨论(0)
  • 2020-12-04 07:38

    If you require a regular expression, use search(). Otherwise, indexOf() is going to be faster.

    0 讨论(0)
  • 2020-12-04 07:38

    IndexOf() - it accepts string literals or string objects but not regular expressions. It also accepts a zero-based integer value to start its search from, e.g.:

    1. "babyelephant".indexOf("e"); // gives you 4
    2. "babyelephant".indexOf("e",5); // gives you 6 as the search starts from 6th position or 5th index.
    3. var m= /e/; "babyelephant".indexOf(m); //gives -1 as it doesnt accepts regular expressions.

    Search() - accepts both string literals or string objects and regular expressions. But it doesn't accepts a index to start the search from.

    0 讨论(0)
提交回复
热议问题