Method 1 : Using Match
match() method retrieves the result of matching a string against a regular expression.
<script> var str = "Hello, codemen. How are you?"; console.log((str.match(/y/g) || ).length); </script>
Method 2: Using Split
split() method divides a
String into an ordered list of substrings, puts these substrings into an array, and returns the array. After that we find the lenght of array and minus 1.
<script> var str = "Hello, codemen. How are you?"; console.log((str.split("o").length - 1)); </script>