How to use String.prototype.repeat() and String.prototype.startsWith() In Javascript
This approach repeats a substring until it equals the input string’s length. Then, it checks if the input string starts with this repeated substring, indicating that the string is entirely made up of the same substring.
Example:
function isEntirelyMadeUpOfSameSubstring(str) {
const len = str.length;
for (let i = 1; i <= len / 2; i++) {
const substring = str.substring(0, i);
if (substring.repeat(len / i) === str) {
return true;
}
}
return false;
}
console.log(isEntirelyMadeUpOfSameSubstring("abcabcabc")); // Output: true
console.log(isEntirelyMadeUpOfSameSubstring("abcdefg")); // Output: false
Output
true false
How to check a string is entirely made up of the same substring in JavaScript ?
In this article, we are given a string and the task is to determine whether the string is made up of the same substrings or not.