We can use the indexOf
method to return the index of the first instance of the substring in a string.
Therefore, we can use that to check if a string is repeated by checking if the index of the substring after the first instance is different from the length of the string.
To do this, we can write:
const check = (str) => {
return (str + str).indexOf(str, 1) !== str.length;
}
console.log(check('abcabc'))
console.log(check('abc123'))
We find the index of str
by starting the search from index 1 to see if it’s different from str.length
.
If it is, that means str
is repeated in the string once.
Therefore, the first console log is true
and the second console log is false
.
Use Regex Capturing Group
A more versatile way to search for repeated strings is to use regex capturing groups.
For instance, we can write:
const check = (str) => {
return /^(.+)\1+$/.test(str)
}
console.log(check('abcabc'))
console.log(check('abcabcabc'))
console.log(check('abc123'))
to check for repeated substrings with check
by checking ifstr
is repeated throughout the string.
Therefore, the first 2 console logs log true
and the last one logs false
.