Finding the longest consecutive appearance of a character in another string using JavaScript

Problem

We are required to write a JavaScript function that takes in a string as the first argument and a single character as the second argument.

Our function should count and return the longest consecutive appearance of the character in the string.

Approach

We'll iterate through the string and track the current consecutive count and maximum count found so far. When we encounter the target character, we increment the counter. When we encounter a different character, we reset the counter.

Example

Following is the code ?

const str = 'abcdaaadse';
const char = 'a';

const countChars = (str = '', char = '') => {
   const arr = str.split('');
   let c = 0, max = 0;
   
   for (let i = 0; i  max) {
            max = c;
         }
      } else {
         if (c > max) {
            max = c;
         }
         c = 0;
      }
   }
   return max;
};

console.log(countChars(str, char));

Output

3

How It Works

In the string 'abcdaaadse', the character 'a' appears consecutively three times at positions 4, 5, and 6. The algorithm tracks this sequence and returns 3 as the longest consecutive count.

Alternative Approach Using Regular Expressions

const countCharsRegex = (str = '', char = '') => {
   const escapedChar = char.replace(/[.*+?^${}()|[\]\]/g, '\$&');
   const regex = new RegExp(escapedChar + '+', 'g');
   const matches = str.match(regex) || [];
   
   return Math.max(...matches.map(match => match.length), 0);
};

console.log(countCharsRegex('abcdaaadse', 'a'));
console.log(countCharsRegex('hello', 'l'));
3
2

Conclusion

Both approaches effectively find the longest consecutive appearance of a character. The loop-based method is more straightforward, while the regex approach is more concise but requires escaping special characters.

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

268 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements