Categories
JavaScript Answers

How to check if a string is entirely made of the same substring with JavaScript?

Spread the love

Sometimes, we want to check if a string is entirely made of the same substring with JavaScript.

In this article, we’ll look at how to check if a string is entirely made of the same substring with JavaScript.

How to check if a string is entirely made of the same substring with JavaScript?

To check if a string is entirely made of the same substring with JavaScript, we can use the indexOf method with a string that concatenated with itself.

For instance, we write

const check = (str) => {
  return (str + str).indexOf(str, 1) !== str.length;
};

to check if the start index of str in str + str when searching from index 1 isn’t str.length.

If this is true, then str isn’t entirely made of the same substring as itself.

Conclusion

To check if a string is entirely made of the same substring with JavaScript, we can use the indexOf method with a string that concatenated with itself.

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 *