What is the best method for counting the number of times a string appears within a string using JS?
For example:
count("fat math cat", "at") returns 3
What is the best method for counting the number of times a string appears within a string using JS?
For example:
count("fat math cat", "at") returns 3
Share
Improve this question
edited Mar 4, 2013 at 13:44
j0k
22.8k28 gold badges81 silver badges90 bronze badges
asked Nov 3, 2011 at 16:48
methuselahmethuselah
13.2k52 gold badges176 silver badges333 bronze badges
6 Answers
Reset to default 6Use a regex and then the number of matches can be found from the returned array. This is the naive approach using regex.
'fat cat'.match(/at/g).length
To protect against cases where the string doesn't match, use:
( 'fat cat'.match(/at/g) || [] ).length
Here:
function count( string, substring ) {
var result = string.match( RegExp( '(' + substring + ')', 'g' ) );
return result ? result.length : 0;
}
Don't use this, it's overplicated:
function count(sample, searchTerm) {
if(sample == null || searchTerm == null) {
return 0;
}
if(sample.indexOf(searchTerm) == -1) {
return 0;
}
return count(sample.substring(sample.indexOf(searchTerm)+searchTerm.length), searchTerm)+1;
}
Can use indexOf
in a loop:
function count(haystack, needle) {
var count = 0;
var idx = -1;
haystack.indexOf(needle, idx + 1);
while (idx != -1) {
count++;
idx = haystack.indexOf(needle, idx + 1);
}
return count;
}
function count(str,ma){
var a = new RegExp(ma,'g'); // Create a RegExp that searches for the text ma globally
return str.match(a).length; //Return the length of the array of matches
}
Then call it the way you did in your example. count('fat math cat','at');
You can use split
also:
function getCount(str,d) {
return str.split(d).length - 1;
}
getCount("fat math cat", "at"); // return 3