How to Tell if a String Contains a Substring in Javascript

Javascript comes with some pretty good support for determining if a string contains a substring.

There is the newer includes function which was introduced in ES2015 which allows you to tell if a string contains a substring. This function returns a boolean value of true or false.

'our example string'.includes('example')

// returns true

Alternatively, if you need to either:

  • Have support for older versions of Javascript
  • Need to not only know if a string contains a substring, but also it’s position within the string..

Then indexOf is a better match for you.

It works as follows:indexOf(search_string, position)

The second argument, position, is not mandatory as shown in the below examples:

'our example string'.indexOf('example') !== -1

// returns true

'our example string'.indexOf('example', 7) !== -1

// returns false

'our example string'.indexOf('example', 2) !== -1

// returns true