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

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

提交回复
热议问题