 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Can one string be repeated to form other in JavaScript
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 −
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) && i > 2) {          return -1       }       current += str1       i += 1    } } console.log(countRepeat(str1, str2)); Output
3
Advertisements
 