Fastest way to check a string contain another substring in JavaScript?
You have three possibilites:
Regular expression:
(new RegExp('word')).test(str) // or /word/.test(str)
indexOf
:str.indexOf('word') !== -1
includes
:str.includes('word')
Regular expressions seem to be faster (at least in Chrome 10).
Performance test - short haystack
Performance test - long haystack
**Update 2011:**
It cannot be said with certainty which method is faster. The differences between the browsers is enormous. While in Chrome 10 indexOf
seems to be faster, in Safari 5, indexOf
is clearly slower than any other method.
You have to see and try for your self. It depends on your needs. For example a case-insensitive search is way faster with regular expressions.
Update 2018:
Just to save people from running the tests themselves, here are the current results for most common browsers, the percentages indicate performance increase over the next fastest result (which varies between browsers):
Chrome: indexOf (~98% faster) <-- wow
Firefox: cached RegExp (~18% faster)
IE11: cached RegExp(~10% faster)
Edge: indexOf (~18% faster)
Safari: cached RegExp(~0.4% faster)
Note that cached RegExp is: var r = new RegExp('simple'); var c = r.test(str);
as opposed to: /simple/.test(str)
The Fastest
- (ES6) includes
var string = "hello", substring = "lo"; string.includes(substring);
- ES5 and older indexOf
var string = "hello", substring = "lo"; string.indexOf(substring) !== -1;
http://jsben.ch/9cwLJ
Does this work for you?
string1.indexOf(string2) >= 0
Edit: This may not be faster than a RegExp if the string2 contains repeated patterns. On some browsers, indexOf may be much slower than RegExp. See comments.
Edit 2: RegExp may be faster than indexOf when the strings are very long and/or contain repeated patterns. See comments and @Felix's answer.