JavaScript: indexOf vs Match when searching for strings?

Unlike readability, are there any noticeable differences (possibly performance) between use

str.indexOf("src") 

and

 str.match(/src/) 

I personally prefer match (and regexp), but colleagues seem to go the other way. We were wondering if this is important ...?

EDIT:

At first, I had to say that this is for functions that will perform partial matching of a simple string (to get identifiers in class attributes for JQuery), and not for a full search for regular expressions using wildcards, etc.

 class='redBorder DisablesGuiClass-2345-2d73-83hf-8293' 

Thus, its difference between:

 string.indexOf('DisablesGuiClass-'); 

VS

 string.match(/DisablesGuiClass-/) 
+57
javascript string regex client
Jan 21 2018-11-11T00:
source share
10 answers

RegExp is really slower than indexOf (you can see it here ), although usually this should not be a problem. With RegExp, you also need to make sure the string is properly escaped, which is an extra thing to think about.

Both of these problems aside, if two tools do exactly what you need, why not choose a simpler one?

+51
Jan 21 2018-11-11T00:
source share

Your comparison may not be entirely fair. indexOf used with regular strings and therefore very fast; match takes a regex - of course, it can be slower compared, but if you want to execute a regex, you won't go far with indexOf . Regular expression mechanisms, on the other hand, can be optimized and have improved performance in recent years.

In your case, when you are looking for a shorthand string, indexOf should be enough. However, there is another application for regular expressions: if you need to match whole words and want to avoid substring matches, then regular expressions give you "anchor boundary snaps". For example:

 indexOf('bar') 

will find bar three times in bar, fubar, barmy , whereas

 match(/\bbar\b/) 

only bar will match if it is not part of a longer word.

As you can see in the comments, some comparisons have been made that show that a regular expression can be faster than indexOf - if it is performance critical, you may need a profile of your code.

+19
Jan 21 2018-11-11T00:
source share

If you are trying to find case-insensitive substrings, match seems to be faster than a combination of indexOf and toLowerCase()

Check here - http://jsperf.com/regexp-vs-indexof/152

+8
Oct 07 '14 at 12:54 on
source share

You ask if str.indexOf('target') or str.match(/target/) preferred. As other posters suggested, the use cases and return types of these methods are different. The first asks: "Where in str can I first find 'target' ?" The second asks: " str matches a regular expression, and if so, what are all the matches for any related capture groups?"

The problem is that none of them are designed specifically to ask a simpler question: "does the string contain a substring?" There is something that is explicitly intended for this:

 var doesStringContainTarget = /target/.test(str); 

There are several advantages to using regex.test(string) :

  • It returns a boolean value that bothers you
  • This is more effective than str.match(/target/) (and rivals str.indexOf('target') )
  • If for some reason str is undefined or null , you will get false (the desired result) instead of throwing a TypeError
+6
Jun 06 '16 at 18:16
source share

Using indexOf should theoretically be faster than a regular expression when you are just looking for some plain text, but you should do some benchmarking yourself if you are concerned about performance.

If you prefer match , and it is fast enough for your needs, go after it.

Why do I agree with your colleagues on this issue: I would use indexOf when searching for a simple string and use match , etc. only when I need the extra functionality provided by regular expressions.

+5
Jan 21 2018-11-11T00:
source share

indexOf performance will be at least slightly faster than match . It all comes down to a specific implementation. When deciding what to use, ask yourself the following question:

Will an integer index suffice or do I need RegExp functionality a match result?

+4
Jan 21 2018-11-11T00:
source share

Return Values ​​Differ

Besides the performance implications that are being addressed by the other answers, it is important to note that the return values ​​for each method are different; therefore, methods cannot be simply replaced without changing your logic.

Return Value .indexOf : integer

The index inside the calling String object of the first occurrence of the specified value, starting the search from fromIndex .
Returns -1 if the value is not found.

Return Value .match : array

An array containing the entire result of the match and any copied matching results.
Returns null if there were no matches.

Because .indexOf returns 0 , if the calling line starts with the specified value, the simplest true test will fail.

For example:

Given this class ...

 class='DisablesGuiClass-2345-2d73-83hf-8293 redBorder' 

... return values ​​for each will differ:

 // returns `0`, evaluates to `false` if (string.indexOf('DisablesGuiClass-')) { … // this block is skipped. } 

against.

 // returns `["DisablesGuiClass-"]`, evaluates to `true` if (string.match(/DisablesGuiClass-/)) { … // this block is run. } 

The correct way to run a true test with a return from .indexOf is to check for -1 :

 if (string.indexOf('DisablesGuiClass-') !== -1) { // ^returns `0` ^evaluates to `true` … // this block is run. } 
+3
May 10 '16 at 19:40
source share

always use indexOf for substrings and match to exist only when you really need it. those. if you were looking for the word src in a string that might also contain altsrc , then aString.match(/\bsrc\b/) really more suitable.

0
Jan 21 '11 at 11:17
source share

Remember Internet Explorer 8 does not understand indexOf . But if none of your users will use ie8 (Google analytics will tell you) than omit this answer. possible solution to fix ie8: How to fix Array indexOf () in JavaScript for Internet Explorer browsers

0
Mar 20 '17 at 14:57
source share

Here are all possible ways (relatively) to search for a string

//one. includes (introduced in ES6)

 var string = "string to search for substring", substring = "sea"; string.includes(substring); 

// 2. string.indexOf

 var string = "string to search for substring", substring = "sea"; string.indexOf(substring) !== -1; 

// 3. RegExp: test

 var string = "string to search for substring", expr = /sea/; // no quotes here expr.test(string); 

//four. string.match

 var string = "string to search for substring", expr = "/sea/"; string.match(expr); 

//5. string.search

 var string = "string to search for substring", expr = "/sea/"; string.search(expr); 

Here is the source: https://koukia.ca/top-6-ways-to-search-for-a-string-in-javascript-and-performance-benchmarks-ce3e9b81ad31

Benchmarks seem to be twisted specifically for es6 includes, read the comments.

In summary:

if you don’t need matches. => Or you need a regular expression and therefore use a test . Otherwise, es6 includes or indexOf . Still the test against indexOf is close.

And for includes vs indexOf:

They seem to be the same: https://jsperf.com/array-indexof-vs-includes/4 (if it were otherwise, it would be weird, they basically do the same thing, except for the differences they expose, check it out )

And for my own test. here it is http://jsben.ch/fFnA0. You can test it (it depends on the browser) [test several times] here, how it was done (launching indexOf multiple times and includes one hit of the other, and they are close). So they are the same. [the same test platform is used here as in the article above].

enter image description here enter image description here

But the long text version (8 times longer) http://jsben.ch/wSBA2

enter image description here

I tested both chrome and firefox, the same thing.

Note that jsben.ch does not handle memory overflow (or limits correctly. It does not display any messages), so the result may not be correct if you add more than 8 duplicates of text (8 work well). But the conclusion is for a very large text - all three work the same way. Otherwise for short indexOf and include are the same and testing is a little slower. or it may be the same as it seemed in chrome (firefox 60 is slower).

Check out jsben.ch: don’t worry if you get inconsistent results. Try a different time and see if it matches or not. Change your browser, sometimes they just do not work correctly. Error or bad memory handling. Or something.

eg:

enter image description here

Here is also my jsperf test (details and graphing for multiple browsers)

(chrome top)

plain text https://jsperf.com/indexof-vs-includes-vs-test-2019
Summary: includes and indexOf have the same performance. the test is slower.

enter image description here enter image description here (it seems all three perform the same in chrom)

Long text (12 times longer than normal) https://jsperf.com/indexof-vs-include-vs-test-2019-long-text-str/
Summary: All three perform the same. (chrome and firefox) enter image description here

very short line https://jsperf.com/indexof-vs-includes-vs-test-2019-too-short-string/
Summary: includes and indexOf do the same and test slower.

enter image description here

Note: about the benchmark above. For a very short string version (jsperf) there was a big mistake for chrome. Seeing with my eyes. about 60 samples were performed for both indexOf and includes the same method (repeated many times). And the test is a little smaller and so slower. don't be fooled by the wrong schedule. This is clearly wrong. The same test works fine for Firefox, of course, this is a mistake.

Here is an illustration: (the first image was a test on Firefox) enter image description here waaaa. Suddenly indexOf became a superman. But, as I said, I did a test and looked at the number of samples, which was about 60. Both indexOf and include, and they did the same. Error on jspref . Other than this (possibly due to a memory constraint problem) everything else was consistent, it gives more details. And you see how much is happening in real time.

Final resume

indexOf vs. includes => Same performance

test => may be slower for short lines or text. And the same goes for long texts. And that makes sense for the overhead that the regex engine adds. In chrome, it seemed completely unimportant.

0
Feb 05 '19 at 16:32
source share



All Articles