How To Check for a Substring in JavaScript

Learn to use .indexOf() and .includes()

Checking for a substring seems like a fairly straightforward task…

Yet, as with many things programming, there are considerations that can easily be overlooked as well as multiple ways to solve the same issue.

In JavaScript, there are two built-in functions — .indexOf() and .includes() — that accomplish the task at hand.


The .indexOf() Method

This method is the most universally available (and thus, reliable) technique to search for a substring.

Using indexOf() is going to return the index where the substring begins. As indexes begin at 0, the method will return -1 if the substring is not found.

We can make a very simple function to take this return value and interpret it as a true or false to explicitly answer the question: “Is the substring present?”

function foundSubstring(haystack,needle) {
   if(haystack.indexOf(needle) >= 0) {
      return true;
   } else {
      return false;
}
var text = "Hello World";
console.log(foundSubstring(text,"llo")) // true

The .includes() Method

This method more directly answers the question as it returns a true or false. The result is an implementation that reads more clearly.

let text = "Hello World";
console.log(text.includes("llo")); // true

The challenge with using this method is that it is not universally supported. Released in ECMAScript6, .includes() is widely available but not universally so.