Javascript string contains substring with performance comparison
I’ve rounded up and tested few performant Javascript methods for checking if a string contains a substring.
For all examples please consider var string = “Hello World”; and var substring = “World”;
- Javascript ES5 indexOf() method – FASTEST
string.indexOf(substring);
- Javascript Lodash library includes() method – 90% slower
_.includes(string, substring);
- Javascript ES6 includes() method – 94% slower
string.includes(substring);
- Javascript ES5 match() method – 99% slower
string.match(new RegExp(substring));
- Javascript ES5 test() method – 99% slower
new RegExp(substring).test(string);
For benchmarking I’ve used this JSPERF test setup.