Readability aside, are there any discernable differences (performance perhaps) between using
str.indexOf("src")
and
If you're trying to search for substring occurrences case-insensitively then match
seems to be faster than a combination of indexOf
and toLowerCase()
Check here - http://jsperf.com/regexp-vs-indexof/152
RegExp is indeed slower than indexOf (you can see it here), though normally this shouldn't be an issue. With RegExp, you also have to make sure the string is properly escaped, which is an extra thing to think about.
Both of those issues aside, if two tools do exactly what you need them to, why not choose the simpler one?
Aside from the performance implications, which are addressed by other answers, it is important to note that the return values for each method are different; so the methods cannot merely be substituted without also changing your logic.
Return value of .indexOf: integer
The index within the calling
String
object of the first occurrence of the specified value, starting the search atfromIndex
.
Returns-1
if the value is not found.
Return value of .match: array
An Array containing the entire match result and any parentheses-captured matched results.
Returnsnull
if there were no matches.
Because .indexOf
returns 0
if the calling string begins with the specified value, a simple truthy test will fail.
For example:
Given this class…
class='DisablesGuiClass-2345-2d73-83hf-8293 redBorder'
…the return values for each would differ:
// returns `0`, evaluates to `false`
if (string.indexOf('DisablesGuiClass-')) {
… // this block is skipped.
}
vs.
// returns `["DisablesGuiClass-"]`, evaluates to `true`
if (string.match(/DisablesGuiClass-/)) {
… // this block is run.
}
The correct way to run a truthy test with the return from .indexOf
is to test against -1
:
if (string.indexOf('DisablesGuiClass-') !== -1) {
// ^returns `0` ^evaluates to `true`
… // this block is run.
}