Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
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
Check if a string is entirely made of the same substring JavaScript
We are required to write a JavaScript function that takes in a string. It should return true or false based on whether the input consists of a repeated character sequence.
The length of the given string is always greater than 1 and the character sequence must have at least one repetition.
For example −
- "aa" should return true because it entirely contains two strings "a"
- "aaa" should return true because it entirely contains three string "a"
- "abcabcabc" should return true because it entirely containas three strings "abc"
- "aba" should return false because it at least there should be two same substrings and nothing more
- "ababa" should return false because "ab" exists twice but "a" is extra so false
Example
const checkCombination = (str = '') => {
if( str.length==1 ) {
return true;
};
for(let i = 1; i <= str.length / 2; i++){
if(str.length % i !== 0){
continue;
}
const sub = str.substring(0, i);
if(isRepeating(sub, str)){
return true;
};
};
return false;
}
const isRepeating = (sub, str) => {
if(str.length > sub.length){
let left = str.substring(0,sub.length);
let right = str.substring(sub.length, str.length);
return left===sub && isRepeating(sub,right);
};
return str === sub;
}
console.log(checkCombination('aa'));
console.log(checkCombination('aaa'));
console.log(checkCombination('abcabcabc'));
console.log(checkCombination('aba'));
console.log(checkCombination('ababa'));
Output
This will produce the following output −
true true true false false
Advertisements