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 true if the string is formed by repeating a pattern
  • Returns false if 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:

  1. Outer loop: Tests pattern lengths from 1 to string length รท 2
  2. Divisibility check: Only considers lengths that divide the string evenly
  3. Inner loop: Compares each character with the character at pattern length distance
  4. 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.

Updated on: 2026-03-15T23:19:00+05:30

875 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements