Is the second string a rotated version of the first string JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in two strings, say str1 and str2. We are required to determine whether or not the second string is a rotated version of the first string.

For example− If the input strings are −

const str1 = 'abcde';
const str2 = 'cdeab';

Then the output should be true because str2 is indeed made by shifting 'ab' to the end of string in str1.

Example

const str1 = 'abcde';
const str2 = 'cdeab';
const isRotated = (str1, str2) => {
   if(str1.length !== str2.length){
      return false
   };
   if( (str1.length || str2.length) === 0){
       return true
   };
   for(let i = 0; i < str1.length; i++){
      const reversed = str1.slice(i).concat(str1.slice(0, i));
      if(reversed === str2){
         return true
      };
   }
   return false;
};
console.log(isRotated(str1, str2));

Output

And the output in the console will be −

true
raja
Published on 21-Nov-2020 06:11:14
Advertisements