Check if a string contains a substring in Javascript

You can find a substring in a string using a classic indexOf() or the new ES6 includes() in Javascript. It’s very easy to do in Javascript programming. If you want a search particular word like a “Hello” then you have to use a regex (regular expression).

Methods to Check if a string contains substring JavaScript

  • indexOf() 
  • includes()

1. String.includes() Method

This method is introduced in ES6, it’s very easy to use and returns a boolean value. See below example only support ES6.

<!DOCTYPE html> 
<html> 
<body> 
<p id="c1"></p> 
<p id="c2"></p>
<script> 
  

   // ES6 only
    var str = "EyeHunts";
    
    var check1 = str.includes('Eye'); 
    var check2 = str.includes('ABC'); 
    document.getElementById("c1").innerHTML = check1; 
    document.getElementById("c2").innerHTML = check2; 
  
</script> 
  
</body> 
</html> 

Output:

Check if a string contains substring JavaScript

2. String.indexOf() Method

The indexof() method returns a substring is found, it returns the index of the character that starts the string otherwise return -1.

<!DOCTYPE html> 
<html> 
<body> 
<p id="c1"></p> 
<p id="c2"></p>
<script> 
  

var str = "EyeHunts Tutorial";
        if (str.indexOf('Hunts') > -1) { // returns `-1` if it is not present.
         // display this
            document.getElementById("c1").innerHTML = str.indexOf('Hunts');
        } else {
            document.getElementById("c2").innerHTML = "not found"; 
        }
        	
  
</script> 
  
</body> 
</html> 

Output: 3

Note:

  • includes doesn’t have Internet Explorer support, though. In ECMAScript 5 or older environments, use String.prototype.indexOf.
  • Both includes() and indexOf() method is case sensitive and also supports the offset parameter:

Do comment if you knew another method to find substring or have any doubts.

Note: The Examples are tested on Safari browser (Version 12.0.2) and Chrome.
OS: macOS 10.14 Mojave
Code: HTML 5 Version


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.