How to Check Whether a String Contains a Substring in JavaScript

Answer: Use the indexOf() Method

The indexOf() method is the simplest and most efficient way to determine whether a string has sub-strings in JavaScript. This returns the index, or the position of the sub string’s first appearance within the string. If there is no match, it returns -1. Here’s an example:

<script>
    // Sample string
    var str = "The quick brown fox jumps over the lazy dog."
    
    // Check if the substring exists inside the string
    var index = str.indexOf("fox");    
    if(index !== -1){
        alert("Substring found!");
    } else{
        alert("Substring not found!");
    }
</script>

The includes() method can be used in ES6 for checking if the index contains a sub-string. This method returns  true or  false , not the index. Let’s look at an example.

<script>
    // Sample string
    var str = "The quick brown fox jumps over the lazy dog."
    
    // Check if string contains substring
    if(str.includes("fox")){
        alert("Substring found!");
    } else{
        alert("Substring not found!");
    }
</script>

To learn more about the new features in JavaScript ES6 please visit our tutorial JavaScript ES6 Features.

You can also use the  search() method (using regular expressions) to search for a specific piece of text or a pattern within a string. The search() method returns an indexOf() of the first match, and returns -1 if there are no matches.To learn more about the new features in JavaScript ES6 please visit our tutorial JavaScript ES6 Features.

<script>
    // Sample string
    var str = "Color red looks brighter than color blue."
    
    // Search the string for a match
    var index = str.search(/color/i);  
    if(index !== -1){
        alert("Substring found!");
    } else{
        alert("Substring not found!");
    }
</script>