dwilbank
dwilbank

Reputation: 2520

Why does this vowel counting fail?

function VowelCount(str) {
  var counter=0;
  for(i=0; i<str.length; i++)
  {
    if (/[AEIOUaeiou]/g.test(str[i]))
    {
      counter += 1;
    }
  }
  return counter; 
}

VowelCount("aaaeeebziiiooouu");

This returns "14" on repl.it, but returns only "7" on coderbyte.

What have I missed?

Upvotes: 0

Views: 305

Answers (3)

elclanrs
elclanrs

Reputation: 94101

You could just use match and count its length:

function vowelCount(str) {
  return (str.match(/[aeiou]/gi) || []).length;
}

What have I missed?

Edit: Your code works fine here http://jsbin.com/osesoh/1/edit

Upvotes: 1

plalx
plalx

Reputation: 43718

While others are right and you should use match instead. You asked why it wasn't working and it's because you set the g flag on your regex, so it will keep track of the lastIndex of the previous match and start looking from that index on for subsequent matches.

E.g.

var rx = /a/g;

rx.test('aa'); //true

console.log(rx.lastIndex); //1

rx.test('a'); //false

Upvotes: 2

leviathanbadger
leviathanbadger

Reputation: 1712

@user1544566 discovered the answer to this question and posted it in the comments, but he didn't write an answer for it. He said:

coderbyte hates the extra g (thanks Mr. Hazmat) Removing the g makes everything work.

Apparently, Coderbyte runs the code you submitted incorrectly. It appears you've found a bug. I'd consider reporting it to them.

Upvotes: 1

Related Questions