# Can one string be repeated to form other in JavaScript

JavascriptWeb DevelopmentFront End Technology

## Problem

We are required to write a JavaScript function that takes in two strings, str1 and str2, as the first and the second argument.

Our function should return the minimum number of times we should repeat string str1 so that string str2 is a substring of it. If it is impossible for str2 to be a substring of a after repeating it, we should return -1

For example, if the input to the function is

Input

const str1 = 'wxyz';
const str2 = 'yzwxyzwx';

Output

const output = 3;

Output Explanation

We return 3 because by repeating a three times "abcdabcdabcd", b is a substring of it.

## Example

Following is the code −

Live Demo

const str1 = 'wxyz';
const str2 = 'yzwxyzwx';
const countRepeat = (str1 = '', str2) => {
let i = 1
let current = str1
while (true) {
if (current.indexOf(str2) >= 0) {
return i
}
if ((current.length > str2.length * 2) &amp;&amp; i > 2) {
return -1
}
current += str1
i += 1
}
}
console.log(countRepeat(str1, str2));

## Output

3