0

How can i count character in word with jQuery?

function count(word, character)
{
   return ???;
}

for example:

count('atesta', 'a'); // should return 2
count('testaaa', 'a'); // should return 3

etc

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • 2
    You can't. jQuery does not provide any string methods. You have to use plain JavaScript for that. – Felix Kling Jun 15 '13 at 21:59
  • `word.match(/a/g).length` – elclanrs Jun 15 '13 at 21:59
  • @elclanrs That's not extremely helpful because `'a'` is contained in a variable so you have to show the way to do it with a dynamically-constructed regex. – ErikE Jun 15 '13 at 22:01
  • @ErikE: Yeah, I wouldn't even make a function for this, I would just do it inline, reads well. That's why I posted as comment though. – elclanrs Jun 15 '13 at 22:02

1 Answers1

3

Why must everything be in jQuery?

function count(haystack, needle) {
    return haystack.split(needle).length-1;
}
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592