How to get the number of a character in a string in JavaScript

In this Article we will go through how to get the number of a character in a string only using single line of code in JavaScript. This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => Arrow Function.

Let's define this short function:

const characterCount = (str, char) => str.split(char).length - 1;

#Or

const characterCount = (str, char) => str.replace((new RegExp(String.raw`[^${char}]`, 'g')), '').length;

#Example

characterCount('192.168.1.1', '.');     // 3
characterCount('star wars', 's');       // 2