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
Use 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;
}
You can use split
also:
function getCount(str,d) {
return str.split(d).length - 1;
}
getCount("fat math cat", "at"); // return 3
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;
}
Don't use this, it's overcomplicated:
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;
}
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');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.