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

后端 未结 8 2005
情歌与酒
情歌与酒 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: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

提交回复
热议问题