Computer >> Computer tutorials >  >> Programming >> Javascript

Is the string a combination of repeated substrings in JavaScript


Problem

We are required to write a JavaScript function that takes in a string of characters as the only argument. Our function needs to check if the string str can be constructed by taking a substring of it and appending multiple copies of the substring together.

For example, if the input to the function is −

const str = 'thisthisthisthis';

Then the output should be −

const output = true;

Output Explanation:

Because the string is made by appending ‘this’ string repeatedly.

Example

The code for this will be −

const str = 'thisthisthisthis';
const repeatedSubstring = (str = '') => {
   const {length} = str;
   const checkSubString = ss => {
      const m = ss.length;
      for (let i = 0; i < length; i += m)
         for (let j = 0; j < m; j++)
            if (str[i+j] !== ss[j])
               return false;
      return true;
   };
   let factor = 2, len;
   while (length/factor >= 1){
      while (length % factor) factor++;
      len = length/factor;
      if (checkSubString(str.substring(0,len))){
         return true;
      };
      factor++;
   };
   return false;
};
console.log(repeatedSubstring(str));

Code Explanation:

Firstly, we set up substring pattern checking function.

Then we iterated through all possible factors that evenly divide string str, to determine if a viable repeat pattern has been found.

Output

And the output in the console will be −

true