Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check if a string is repeating in itself in JavaScript
We are required to write a JavaScript function that takes in a string as the first and the only argument.
The function should detect if the string is a repetition of a same set of characters or not.
If it is a repetition of the same set of characters then we should return true, false otherwise.
For example −
If the input string is −
const str = 'carcarcarcar';
Then the output should be −
const output = true;
because the string 'car' is getting repeated over and over again in the string.
Example
Following is the code −
const str = 'carcarcarcar';
const isRepeating = (str = '') => {
if (!str.length){
return false
};
for(let j = 1; (j <= str.length / 2); j++){
if (str.length % j != 0){
continue
};
let flag = true;
for(let i = j; i < str.length; ++ i){
if(str[i] != str[i - j]){
flag = false;
break;
};
};
if(flag){
return true;
};
};
return false;
};
console.log(isRepeating(str));
Output
Following is the console output −
true
Advertisements