How To Check Strings Are Rotation Of Each Other Or Not In JavaScript

In this article, we learn how to check whether strings are in rotation with each other or not in JavaScript.

For string, rotation check must follow these steps:-

Step 1: Define two string 1 and string 2.

Step 2: To check whether string 2 is the rotation of string 1 then, first check the length of both the strings. If they are not equal, then string 2 cannot be a rotation of string 1.

Step 3: Concatenate string 1 with itself and assign it to string 1.

Step 4: Check the index of string 2 in string 1. If it exists then, string 2 is a rotation of string 1.

Now create an Html file and add the following to it.

<!DOCTYPE html>
<html>
  <body>
    <div>str1 = <span id="str1"></span> </div>
    <div>str2 = <span id="str2"></span></div>
    <div>concat str1 with itself = <span id="concat"></span></div>
    <div id="output"></div>

    <script>
      let str1 = "abcde";  
      let str2 = "deabc";  

      document.getElementById("str1").innerHTML = str1;
      document.getElementById("str2").innerHTML = str2;

      if(str1.length==str2.length){
        str1 = str1 + str1;  
        document.getElementById("concat").innerHTML = str1; 

        if(str1.includes(str2)){
          document.getElementById("output").innerHTML = "string 2 is a rotation of string 1";
        }
        else{
          document.getElementById("output").innerHTML = "string 2 is not a rotation of string 1";
        }
      }
      else{
        document.getElementById("output").innerHTML = "string 2 cannot be a rotation of string 1"
      }
    </script>

  </body>
</html>

Output:-

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories