Tuesday, April 17, 2012

Javascript: Count a string occurence in text


While working on my favorite project I had to count the colons in a string. I was wondering which could be the best solution. I had two methods in my mind to solve that.

The first is the "split" method:
var text = 'text text text: text2: text3::';
var colon_length = text.split(":").length - 1;


The other one is the "RegExp" method:
var text = 'text text text: text2: text3::';
var colon_length = text.match(/:/g).length;


After googling for a while I found a test which one is better:
http://jsperf.com/count-the-number-of-occurances-in-string


Well, that graph is self explanatory I guess :) (Thanks jsPerf.com)



In the mean time I stumbled into this solution which I think is quite interesting:
http://www.codecodex.com/wiki/index.php?title=Count_the_number_of_occurrences_of_a_specific_character_in_a_string#JavaScript

This is the code:
String.prototype.count=function(s1) { 
 return (this.length - this.replace(new RegExp(s1,"g"), '').length) / s1.length;
}


And this is the usage:
// use like this 
test = "this, as you see, is a sentence, containing many ','s";
numberOfCommas = test.count(','); //4
// or 
numberOfSblank = test.count('s '); //2


But because in my project I have to use a minimal amount of global footstep I sticked to the "RegExp" method.