| Viewed 113 times

Get the number of times a character appears in each word in a sentence in Javascript?


Create a function that returns the number of times a character appears in each word in a sentence.

1 Answer
Mohammad Qandeel
Answered
11

This function will return an array containing the number of repeated characters in the text.

It depends on the separation of words based on the spaces between the words in the sentence

 

function charAppears(sentence, char) {
 return sentence.split(' ').reduce((acc, cv) => {
  let result = cv.match(new RegExp(char, "gi"));
  result == null ? acc.push(0) : acc.push(result.length);
  return acc;
 }, []);
}

//example
charAppears('Qandeel academy', 'e')  // [2, 1]


Related Questions