This post will discuss how to check whether a string contains another string as its substring in JavaScript.

1. Using String.prototype.includes() function

The includes() method can be used to check whether a given string includes another string or not. It returns true if the search string is found within the given string; false otherwise. Here’s how the code would look like:

Download  Run Code

 
This method has been introduced with the ES6 and may not be available in all JavaScript implementations yet. However, MDN has a simple polyfill for this method:

2. Using Lodash Library

If you are using lodash library, the _.includes method will be useful:

Download Code

3. Using String.prototype.indexOf() function

The indexOf() method returns the index of the first occurrence of the target or -1 when the target string is not found. The following example demonstrates its usage.

Download  Run Code

Finally, you can also use the search() method to check if the source string contains the target string. The following example would return the index of the first match of the target in the given string, or -1 if it found no match.

Download  Run Code

That’s all about determining whether a string contains another string as a substring in JavaScript.