Javascript string contains substring with performance comparison
- JAVASCRIPT
- CODING TIPS
- CONTAINS
Published on 2018-08-13
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);
Copy code to the clipboardJavascript Lodash library includes() method – 90% slower
_.includes(string, substring);
Copy code to the clipboardJavascript ES6 includes() method – 94% slower
string.includes(substring);
Copy code to the clipboardJavascript ES5 match() method – 99% slower
string.match(new RegExp(substring));
Copy code to the clipboardJavascript ES5 test() method – 99% slower
new RegExp(substring).test(string);
Copy code to the clipboard
For benchmarking I've used this JSPERF test setup.
Have you enjoyed the read? Please show your support by sharing it with the world 🙌🏻Share Share Share