Character Count

They have: 39 posts

Joined: Jun 2000

Is it possible in Javascript to count how many times a cahracter e.g. { occurs in a string?

Thanks!

They have: 231 posts

Joined: Feb 2000

Yes. You can loop through the entire length of a string and increment a counter each time it finds a match.

var myStr = "foo";
var matchChar = "o";

var matchCounter = 0;

for (i = 0; i < myStr.length; i++) {
   if (myStr.charAt(i) == matchChar) {
      matchCounter++;
      }
   }

alert(matchCounter)
'

:: Lloyd Hassell :: http://www14.brinkster.com/lloydh ::

Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.