1

I am trying to count the number of commas and question marks in a given array. Here is what I have so far but it only returns how many commas I have. I am having trouble understanding how to also return how many question marks there are.

var str = 'hello, how are you today? I am not bad and you?'

function checker(str){
  var count = 0
  for(var i = 0; i < str.length; i++){
    if(str[i] == ",")
      count++
  }
  return `There is ${count} comma`
}
checker(str)

//this returns "There is 1 comma"

I know the code only shows to count commas. I am not sure how to also include code to count the question marks.

Audwin Oyong
  • 2,247
  • 3
  • 15
  • 32
6Ortiz
  • 39
  • 1
  • 1
  • 7

1 Answers1

1

The solution is quite straightforward if we apply the same logic you used for counting the commas.

You just need to add another variable for counting the question marks (count2) and include it in the message. Like this:

var str = 'hello, how are you today? I am not bad and you?'

function checker(str) {
  var count = 0
  var count2 = 0
  for (var i = 0; i < str.length; i++) {
    if (str[i] == ",") {
      count++
    } else if (str[i] == "?") {
      count2++
    }
  }
  return `There are ${count} comma(s) and ${count2} question mark(s)`
}
console.log(checker(str));
lealceldeiro
  • 14,342
  • 6
  • 49
  • 80
  • I had tried that before but it kept returning something like 48 commas and 48 question marks. Now i see that I had forgotten to add count2 when trying that solution. Thank you so much! – 6Ortiz Aug 31 '18 at 14:44
  • @6Ortiz Great! If this was useful to you, please [upvote](//stackoverflow.com/privileges/vote-up) this question for future readers and consider [accepting](http://stackoverflow.com/help/someone-answers) it if you think it fits the question requirements. – lealceldeiro Aug 31 '18 at 14:58