Reputation: 31520
Learning javascript and came across something like this:
if (obj.indexOf("someValue") > -1) {
do.something();
}
Without posting the whole script, the indexOf() method was only being used to check for a value in a string.
My question is why you would do that instead of:
if (obj.match(/someValue/g)) {
do.something();
}
Is this for legacy browser support or is it faster for some reason?
Upvotes: 1
Views: 119
Reputation: 911
Well, indexOf()
is a simple string search, while obj.match()
is regExp search. It's just two different things.
When I need to check if is it rainig right now, I just look out the window instead of turning on TV and looking for weather forecast.
P.S.: Btw your "/g
" makes global search, when indexOf()
returns only the first occurrence. So in your case indexOf()
becomes faster (compairing to obj.match()
) as input string becomes longer.
Upvotes: 0
Reputation: 172378
I think the reason is that RegExp match()
is indeed slower than indexOf
You can check here.
From the above site only the code:
<script>
var str = "hello world!";
</script>
5,616,069 Ops/sec Using match time taken is ±3.05% 55% slower
12,306,269 Ops/sec Using indexOf() time taken is ±2.51% fastest
Upvotes: 2
Reputation: 2724
Generally speaking it is really more a question of taste. Some could argue though that indexOf is slightly faster.
Upvotes: 0