Signup/Sign In
PUBLISHED ON: MARCH 15, 2023

JavaScript Program to Check the Number of Occurrences of a Character in the String

To modify and retrieve data from strings in JavaScript, we can employ a number of different techniques. Checking the frequency of a letter in a string is a frequent job. Numerous uses, including text translation and data analysis, can benefit from this. In this piece, we'll look at various methods for writing a JavaScript application that counts the instances of a particular letter in a string. We also have an interactive JavaScript course where you can learn JavaScript from basics to advanced and get certified. Check out the course and learn more from here.

Check Occurrence of a Character Using for Loop

In the beginning, we need to take inputs for both the string as well as the letter to look into. The value of the count variable is taken as 0. The for loop is used to iterate over the string and check the particular letter throughout the whole string. The charAt function is used to check for that particular character present in that index and if that matches with it then the count variable is increased by 1.

// JavaScript program to check the number of occurrences of a character

function countCharacter(str, letter) {
    let count = 0;

    for (let i = 0; i < str.length; i++) {

        // checking for that character in that particular position index
        if (str.charAt(i) == letter) 
            count += 1;
        
    }
    return count;
}

const string = prompt('Enter the string: ');
const letterToCheck = prompt('Enter the letter to check for : ');

//passing parameters and calling the function
const result = countCharacter(string, letterToCheck);

console.log(result);


Enter a string: hello
Enter a letter to check: l
2

conclusion

In conclusion, one frequent job in JavaScript programming is tallying the instances of a letter in a string. We looked at various methods for resolving this issue in this piece, including the use of loops, regular expressions, and the built-in String technique. We went over each method's advantages and disadvantages, as well as gave instances and edge situations to think about. With this information, you can use these methods in your own algorithms to more skillfully evaluate and work with string data.



About the author:
Proficient in the creation of websites. Expertise in Java script and C#. Discussing the latest developments in these areas and providing tutorials on how to use them.