You can use RegExp.exec() to save memory if you are dealing with a large string:
var re = /,/g, str = 'file123,file456,file789', count = 0; while (re.exec(str)) { ++count; } console.log(count);
Demo Comparative Comparison
Performance is about 20% lower than the solution using String.match() , but it helps if you're concerned about memory.
Update
Less sexy but faster:
var count = 0, pos = -1; while ((pos = str.indexOf(',', pos + 1)) != -1) { ++count; }
Demo
Ja͢ck Apr 30 '14 at 10:15 2014-04-30 10:15
source share