Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count characters in strings with or without string.slice

Tags:

javascript

I am trying to learn how this problem has been solved but I am lost at string.slice(0,1) and i++ after that.

What is the need to use the slice method?

The questions is:

Write a function called countChars that accepts two parameters: a string and a character. This function should return a number representing the number of times that the character appears in string.

function countChars(string, character) {
    let count = 0;
    let i = 0;
    while (i < string.length) {
        if (string[i] === character) {
            count++;
        }
        string.slice(0, 1);
        i++;
    }
    return count;
}
like image 922
Shreeya Bhetwal Avatar asked Apr 26 '26 00:04

Shreeya Bhetwal


1 Answers

Nina already solved it using your code, a shorter option would be using String.match

function countChars(string, character) {
  const { length } = string.match(new RegExp(character, 'ig')) || [];
  return length;
}

console.log(countChars('Foobar', 'o'));
like image 150
baao Avatar answered Apr 27 '26 14:04

baao