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.
- Initialize a string to the variable.
- Use the test() method to test a pattern in a string.
- The test() method returns true if the match is found, otherwise, it returns false.
Example 1: This example checks for string geeksgeeksgeeks which is made up of the same substring, so it returns True.
Javascript
let str = "geeksgeeksgeeks" ;
function check(str) {
return /^(.+)\1+$/.test(str)
}
let ans = "String is not made up of same substrings" ;
if (check(str)) {
ans = "String is made up of same substrings" ;
}
console.log(ans);
|
Output
String is made up of same substrings
Example 2: This example checks for string geeksgeekgeeks which is not made up of the same substrings so it returns False.
Javascript
let str = "geeksgeekgeeks" ;
function check(str) {
return /^(.+)\1+$/.test(str)
}
let ans = "String is not made up of same substrings" ;
if (check(str)) {
ans = "String is made up of same substrings" ;
}
console.log(ans);
|
Output
String is not made up of same substrings
Last Updated :
20 Jul, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...