- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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
To Continue Learning Please Login
Login with Google