Quick way to count how many times a character appears in a string in Javascript

My favorite way to count how many times a character appears in a String is str.split("x").length - 1, where str is the String and “x” is the character you are searching for.

For example:


let str = "hi my name is uhded";
console.log(str.split("e").length-1) // 2

The way this work is that the “split” method in Javascript splits the String into an array of substrings.
The value we put as the parameter is the “separator”, meaning the String will be split into an array of substrings separated by the separator (in the above example, the letter “e”). So, “hi, my name is uhded” would get split into 3 substrings:

[“hi my nam”, “ is uhd”, “d”] -> As you can see it was separated (in this example) by the “e” into 3 Strings. This is why when we ask for the length of the array we subtract 1.

Another example:

let str = "hi myeeee name is uhded";
let x = str.split("e");
console.log(x) //["hi my", "", "", "", " nam", " is uhd", "d"]

Please note: This “split” method is typically used to split a String into substrings separated by a comma or any separator but by combining it with “.length-1” it provides this easy way to count how many times a character appears in a String!