Home >>Javascript Programs >Count occurrence of a particular character in a string in JavaScript
In this article, we will see how to count occurrence of a particular character in a string in JavaScript. String in JavaScript is used for input/output data to the user and it is a very popular data type. Today, in this tutorial, we will write a program how we can access each element string and compare it with the particular character.
Let's take an example:<!DOCTYPE html> <html> <body> <script> function displaystr() { setTimeout(function() { var str = document.getElementById('str1').value; var letter = document.getElementById('letter1').value; letter = letter[letter.length-1]; var lCount; for (var i = lCount = 0; i < str.length; lCount += (str[i++] == letter)); document.querySelector('p').innerText = lCount; return lCount; }, 50); } </script> Enter String: <input type="text" id="str1"><br><br> Enter Letter: <input type="text" id="letter1"><br><br> <button onclick="displaystr()">Click for Result</button><br><br> result= <p></p> </body> </html>