Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Check if a string is repeating in itself in JavaScript
In JavaScript, we often need to determine if a string consists of a repeating pattern. This involves checking if the entire string can be formed by repeating a smaller substring multiple times.
For example, the string 'carcarcarcar' is made by repeating 'car' four times, so it should return true. However, 'abcdef' has no repeating pattern, so it should return false.
Problem Understanding
We need to write a function that:
- Takes a string as input
- Returns
trueif the string is formed by repeating a pattern - Returns
falseif no repeating pattern exists
Example Input and Output
Input: 'carcarcarcar' Output: true (pattern: 'car' repeated 4 times) Input: 'abcdef' Output: false (no repeating pattern)
Solution Using Pattern Matching
The algorithm works by testing each possible pattern length from 1 to half the string length:
const str = 'carcarcarcar';
const isRepeating = (str = '') => {
if (!str.length) {
return false;
}
// Test each possible pattern length
for (let j = 1; j
true
true
false
How the Algorithm Works
The solution uses a nested loop approach:
-
Outer loop: Tests pattern lengths from 1 to string length รท 2
-
Divisibility check: Only considers lengths that divide the string evenly
-
Inner loop: Compares each character with the character at pattern length distance
-
Early return: Returns
true as soon as a valid pattern is found
Alternative Solution Using String Methods
Here's a more concise approach using JavaScript's built-in methods:
const isRepeatingAlt = (str) => {
if (!str.length) return false;
// Try each possible pattern length
for (let len = 1; len
true
true
false
Testing Different Cases
const testCases = [
'aa', // pattern: 'a'
'abab', // pattern: 'ab'
'abcabcabc', // pattern: 'abc'
'single', // no pattern
'', // empty string
'a' // single character
];
testCases.forEach(test => {
console.log(`"${test}": ${isRepeating(test)}`);
});
"aa": true
"abab": true
"abcabcabc": true
"single": false
"": false
"a": false
Conclusion
Both approaches effectively detect repeating patterns in strings. The first method uses character-by-character comparison, while the second leverages JavaScript's string methods for a cleaner implementation. Choose based on your preference for performance versus readability.
