red888
red888

Reputation: 31520

Javascript: Why would one use indexOf() to match a value in a string?

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

Answers (4)

haldagan
haldagan

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

Rahul Tripathi
Rahul Tripathi

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

Mathias
Mathias

Reputation: 2724

Generally speaking it is really more a question of taste. Some could argue though that indexOf is slightly faster.

Upvotes: 0

Fez Vrasta
Fez Vrasta

Reputation: 14815

match() uses regex, regex is slower than indexOf().

Upvotes: 1

Related Questions