Check if a string is repeating in itself in JavaScript


We are required to write a JavaScript function that takes in a string as the first and the only argument.

The function should detect if the string is a repetition of a same set of characters or not.

If it is a repetition of the same set of characters then we should return true, false otherwise.

For example −

If the input string is −

const str = 'carcarcarcar';

Then the output should be −

const output = true;

because the string 'car' is getting repeated over and over again in the string.

Example

Following is the code −

const str = 'carcarcarcar';
const isRepeating = (str = '') => {
   if (!str.length){
      return false
   };
   for(let j = 1; (j <= str.length / 2); j++){
      if (str.length % j != 0){
         continue
      };
      let flag = true;
      for(let i = j; i < str.length; ++ i){
         if(str[i] != str[i - j]){
            flag = false;
               break;
         };
      };
      if(flag){
         return true;
      };
   };
   return false;
};
console.log(isRepeating(str));

Output

Following is the console output −

true

Updated on: 23-Jan-2021

609 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements