Tags
Asked 3 years ago
16 Jun 2021
Views 295
Lorna

Lorna posted

Count the number of occurrences of a character in a string in JavaScript

Count the number of occurrences of a character in a string in JavaScript
kord

kord
answered Apr 27 '23 00:00

You can count the number of occurrences of a character in a string in JavaScript by using a combination of the split() and length methods. Here's an example:



var string = "Hello World";
var char = "o";
var count = string.split(char).length - 1;
console.log(count); // Output: 2

In this example, we have a string variable string that contains the text "Hello World", and a character variable char that contains the letter "o". We use the split() method to split the string into an array of substrings using the specified character as a separator, and then subtract 1 from the length of the resulting array to obtain the number of occurrences of the character in the original string.

The resulting value of count will be the number of times the character appears in the string, which in this case is 2.

You can adjust the character variable to count the occurrences of different characters in the string
Post Answer