How to Check If a String Contains Another Substring in JavaScript

There are several methods to check if String contains another Substring in Javascript. Let’s turn to their discussion bellow:

String.includes()

This method searches the sequence of characters in the given string and returns true if sequence of char value exists, otherwise returns false.

Example

<!DOCTYPE html> 
<html>
   <body>
      <p>Click the button to check if the string includes the specified value.</p>
      <button onclick="myFunction()">Check</button>
      <p id="demo"></p>
      <script>
         function myFunction() {
         var str = "Hello guest, welcome to our website.";
         var n = str.includes("guest",);
         document.getElementById("demo").innerHTML = n; }
      </script>
   </body>
</html>

The above-mentioned example returns true.

includes() is not supported in Internet Explorer.

RegExp.test()

This method is much easier to use as it returns a boolean. Compared to the indexOf() method, it returns direct true or false results and can therefore be a good alternative.

String.indexOf

This method returns the position of the first occurrence of a specified value in a string. This indexOf() method simply tests if there is a substring or not. If it is present, it will return the starting index of the substring; if not, it will return -1.

Example

<!DOCTYPE html> 
<html>
   <body>
     <p>Click the button to locate where in the string a specified value occurs.</p>
      <button onclick="myFunction()">Check</button>
      <p id="demo"></p>
      <script>
         function myFunction() {
         var str = "Hello guest, welcome to our website.";
         var n = str.indexOf("welcome");
         document.getElementById("demo").innerHTML = n;}
      </script>
   </body>
</html>

String.contains

This method will directly check if there is a substring or not and return a boolean value.

Use this method with caution, as it became available after ECMAScript 6.

Do you find this helpful?

Related articles