How do I check if a string is entirely made of the same substring?

The length of the given string is always greater than 1 and the character sequence must have at least one repetition.

"aa" // true(entirely contains two strings "a")
"aaa" //true(entirely contains three string "a")
"abcabcabc" //true(entirely containas three strings "abc")

“aba” //false(At least there should be two same substrings and nothing more)
“ababa” //false(“ab” exists twice but “a” is extra so false)

I have created the below function:

function check(str){
if(!(str.length && str.length - 1)) return false;
let temp = ‘’;
for(let i = 0;i<=str.length/2;i++){
temp += str[i]
//console.log(str.replace(new RegExp(temp,“g”),‘’))
if(!str.replace(new RegExp(temp,“g”),‘’)) return true;
}
return false;
}

console.log(check(‘aa’)) //true
console.log(check(‘aaa’)) //true
console.log(check(‘abcabcabc’)) //true
console.log(check(‘aba’)) //false
console.log(check(‘ababa’)) //false

Checking of this is part of the real problem. I can’t afford a non-efficient solution like this. First of all, it’s looping through half of the string.

The second problem is that it is using replace() in each loop which makes it slow. Is there a better solution regarding performance?

#javascript #string #algorithm

5.70 GEEK