How to Count the Occurrence of an Element in a String Using JavaScript?

Estimated read time 1 min read

In JavaScript, you can count the occurrence of an element in a string by using the string method split() and the Array.prototype.reduce() method. The split() method is used to convert the string into an array of substrings, and then the reduce method is used to count the occurrences of a specific element in the array.

Here’s an example:

function countOccurrences(string, char) {
  let arr = string.split('');
  return arr.reduce((acc, curr) => {
    return acc + (curr === char);
  }, 0);

You can call this function and pass in the string and the character you want to count as arguments:

let str = "hello world";
let count = countOccurrences(str, 'l');
console.log(count); // 3

In this example, the function countOccurrences takes a string and a character as arguments. The split method is used to convert the string into an array of characters. The reduce method is then used to iterate over the array and count the occurrences of the character. The accumulator starts at 0 and is incremented by 1 every time the current value equals the character. The final value of the accumulator is returned, which is the count of occurrences.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply