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
Selected Reading
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 the character in the string.
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<arr.length ;i++){
if(arr[i] === char){
c+=1
if(c > max){
max = c;
};
}else{
if(c > max){
max = c;
};
c = 0;
};
};
return max;
};
console.log(countChars(str, char));
Output
3
Advertisements
