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.


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){
      let flag = true;
      for(let i = j; i < str.length; ++ i){
         if(str[i] != str[i - j]){
            flag = false;
         return true;
   return false;


Following is the console output −