Algorithm


  1. Input: Accept the string and the character to be checked as input.

  2. Initialize Counter: Set a counter variable to 0 to keep track of the number of occurrences.

  3. Loop through the String: Use a loop to iterate through each character in the string.

    a. Check if the current character is equal to the target character.

    b. If true, increment the counter.

  4. Output: Display or return the final count of occurrences.

 

Code Examples

#1 Code Example- Check Occurrence of a Character Using for Loop

Code - Javascript Programming

// program to check the number of occurrence of a character

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

    // looping through the items
    for (let i = 0; i  <  str.length; i++) {

        // check if the character is at that position
        if (str.charAt(i) == letter) {
            count += 1;
        }
    }
    return count;
}

// take input from the user
const string = prompt('Enter a string: ');
const letterToCheck = prompt('Enter a letter to check: ');

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

// displaying the result
console.log(result);
Copy The Code & Try With Live Editor

Output

x
+
cmd
Enter a string: school
Enter a letter to check: o
2

#2 Code Example- Check occurrence of a character using a Regex

Code - Javascript Programming

// program to check the occurrence of a character

function countString(str, letter) {

    // creating regex 
    const re = new RegExp(letter, 'g');

    // matching the pattern
    const count = str.match(re).length;

    return count;
}

// take input from the user
const string = prompt('Enter a string: ');
const letterToCheck = prompt('Enter a letter to check: ');

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

// displaying the result
console.log(result);
Copy The Code & Try With Live Editor

Output

x
+
cmd
Enter a string: school
Enter a letter to check: o
2
Advertisements

Demonstration


JavaScript Programing Example to Check the Number of Occurrences of a Character in the String-DevsEnv

Previous
JavaScript Practice Example #3 - Assign 3 Variables and Print Good Way