I need to count the number of occurrences of a character in a string.
For example, suppose my string contains:
var mainStr = \"str1,str2,str3,str4\";
I believe you will find the below solution to be very short, very fast, able to work with very long strings, able to support multiple character searches, error proof, and able to handle empty string searches.
function substring_count(source_str, search_str, index) {
source_str += "", search_str += "";
var count = -1, index_inc = Math.max(search_str.length, 1);
index = (+index || 0) - index_inc;
do {
++count;
index = source_str.indexOf(search_str, index + index_inc);
} while (~index);
return count;
}
Example usage:
console.log(substring_count("Lorem ipsum dolar un sit amet.", "m "))
function substring_count(source_str, search_str, index) {
source_str += "", search_str += "";
var count = -1, index_inc = Math.max(search_str.length, 1);
index = (+index || 0) - index_inc;
do {
++count;
index = source_str.indexOf(search_str, index + index_inc);
} while (~index);
return count;
}
The above code fixes the major performance bug in Jakub Wawszczyk's that the code keeps on looks for a match even after indexOf says there is none and his version itself is not working because he forgot to give the function input parameters.