What is the difference between indexOf() and search()?
Asked Answered
P

9

209

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

Can anyone help clarify this for me?

Penetrant answered 9/12, 2008 at 20:25 Comment(0)
J
239

If your situation requires the use of a regular expression, use the search() method, otherwise; the indexOf() method is more performant.

Jobye answered 9/12, 2008 at 20:29 Comment(4)
any reference to support this claim?Proudfoot
Also, search will evaluate a string into a regex even if you don't want to.Advertisement
@cregox's comment is important - try "hello.".search(".") - it returns 0, not 5 because . is the regex token for "any character"Brigid
'hello'.indexOf(undefined) returns -1, 'hello'.search(undefined) returns 0Underclay
A
44

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

Ability answered 9/12, 2008 at 20:28 Comment(0)
A
18

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

Amorita answered 22/4, 2019 at 12:15 Comment(0)
M
15

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.

Metametabel answered 9/12, 2008 at 20:31 Comment(0)
A
7

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

Check this reference:

Allison answered 9/12, 2008 at 20:30 Comment(0)
M
4

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.

Mohican answered 5/9, 2016 at 14:20 Comment(2)
What does it return for "baby/e/lephant".indexOf(m);?Hygro
good one.. it will return 4..because /e/ string is present..but if you want to find a regex "e" you aren't going to get the desired result. UMM maybe i should modify my answer to indexOf() tries to find the regex as a string literal and not as a regex.Mohican
O
2

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

IndexOf

Search

Ortensia answered 9/12, 2008 at 20:32 Comment(1)
Search does return an offset. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…Towering
A
0

Besides all the other considerations already mentioned indexOf is faster by a very large margin, if you don't need to do funky regex and are just doing a simple find then do not use search. robisrob asked for some evidence so I whipped up a quick test.

Starting...
  IndexOf test - loop count 10000000
  IndexOf test end - duration: 4.600000023841858ms
  Search test - loop count 10000000
  Search test end - duration: 1221.6999999284744ms
All Done

That is a significant difference, only use search if you are going to be using regular expressions.

I can post the test code if anyone is interested.

Acrolein answered 10/1, 2023 at 8:58 Comment(0)
S
-1

Without a regex, there is no practical difference between indexOf and search.

The below example gives a live demo:

function FromSearch() {

  var str = document.getElementById("demo").innerText;
  var n = str.search("difference");
  document.getElementById("Location").innerHTML = n;
}

function FromindexOf() {
  var str = document.getElementById("demo").innerText;
  var n = str.indexOf("difference");
  document.getElementById("Location").innerHTML = n;
}
<p id="demo">Without a <a href='http://www.w3schools.com/js/js_regexp.asp'>regex</a>, there is no practical difference between <a href='http://www.w3schools.com/jsref/jsref_indexof.asp'>indexOf</a> and <a href='http://www.w3schools.com/jsref/jsref_search.asp'>search</a>
</p>

<button onclick="FromSearch()">From search</button>

<button onclick="FromindexOf()">From indexOf</button>

<p>Location of difference in the above sentence is:</p>

<mark id="Location"></mark>
Sunglass answered 15/12, 2015 at 7:2 Comment(1)
There is a significant difference: search converts a string into a RegExp, so for instance, str.search("d........e"); will also match at character 39.Snatch

© 2022 - 2024 — McMap. All rights reserved.