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 seems to be faster, in Safari 5, is clearly slower than any other method.indexOf
indexOf
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)
Firefox: cached RegExp (~18% faster)
IE11: cached RegExp(~10% faster)
Edge: indexOf (~18% faster)
Safari: cached RegExp(~0.4% faster)<-- wow
Note that cached RegExp is: as opposed to: var r = new RegExp('simple'); var c = r.test(str);
/simple/.test(str)