admin管理员组文章数量:1333658
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
本文标签: javascriptCounting the number of times a pattern appears in a stringStack Overflow
版权声明:本文标题:javascript - Counting the number of times a pattern appears in a string - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742346442a2457616.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论