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 clipboard
  • Javascript Lodash library includes() method – 90% slower

    _.includes(string, substring);Copy code to the clipboard
  • Javascript ES6 includes() method – 94% slower

    string.includes(substring);Copy code to the clipboard
  • Javascript ES5 match() method – 99% slower

    string.match(new RegExp(substring));Copy code to the clipboard
  • Javascript ES5 test() method – 99% slower

    new RegExp(substring).test(string);Copy code to the clipboard

For benchmarking I've used this JSPERF test setup.

Rafael Caferati

Full Stack Web Developer, UI/UX Javascript Specialist.

<[{ Part-time developer – full-time geek }]>

Avatar