Categories
JavaScript Answers

How to Check if a JavaScript String is Entirely Made of the Same Substring?

Spread the love

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 .

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *