0

The assignment is counting a specific letter in a string. But the problem is that I don't know how to set capital letter is same with lowercase letter. For example, There are three 'a' in 'aAa', a string.

my code is working well if it distinguishes capital letter and lowercase letter.

function countChar(string, char) {

  var count = 0;
  for (var i = 0; i < string.length; i++) {

    if (string[i] === char) {
      count = count + 1;
    }

  }
  return count;
}
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
Daye Kang
  • 39
  • 4

3 Answers3

0

You could convert both strings to lower case in advance with String#toLowerCase. The other way is possible as well by using String#toUpperCase.

Both methods returns a comparable result.

char = char.toLowerCase();
string = string.toLowerCase();
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

Convert the string to lower case using

.toLowerCase()

function countChar(string, char) {
  string = string.toLowerCase();
  char=char.toLowerCase();
  var count = 0;
  for (var i = 0; i < string.length; i++) {
    if (string[i] === char) {
      count = count + 1;
    }
  }
  return count;
}
console.log(countChar('aAa', 'A'))
ellipsis
  • 12,049
  • 2
  • 17
  • 33
0

In one line you can do:

function countChar(string, char) {
  return string.toLowerCase().split('').reduce((count , x) => (x === char ? count+1 : count), 0);
}

console.log(countChar('aAa', 'a'))
Abraham
  • 8,525
  • 5
  • 47
  • 53