计算图案在字符串中出现的次数
Counting the number of times a pattern appears in a string
使用JS计算字符串在字符串中出现的次数的最佳方法是什么?
例如:
count("fat math cat", "at") returns 3
使用正则表达式,然后可以从返回的数组中找到匹配的数量。这是使用regex的幼稚方法。
'fat cat'.match(/at/g).length
为了防止字符串不匹配的情况,请使用:
( 'fat cat'.match(/at/g) || [] ).length
此处:
function count( string, substring ) {
var result = string.match( RegExp( '(' + substring + ')', 'g' ) );
return result ? result.length : 0;
}
不要使用这个,它太复杂了:
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;
}
可以在循环中使用indexOf
:
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
}
然后用你在例子中的方式来称呼它。count('fat math cat','at');
您也可以使用split
:
function getCount(str,d) {
return str.split(d).length - 1;
}
getCount("fat math cat", "at"); // return 3
相关文章:
- 计算输入中有多少逗号分隔的字符串
- 如何在JavaScript/Node中计算SHA256哈希和Base64字符串编码
- JavaScript:计算字符串中特定整数的实例
- 计算空字符串的值
- 检查字符串是否包含计算
- 以点表示法计算字符串,以从视图中的对象获取相应的值
- 计算字符串中的特定字母
- 计算字符串javascript中的某些单词
- Javascript-修改函数或从字符串中计算函数
- 在不渲染的情况下计算字符串大小
- 计算 jQuery 中字符串中的特殊字符
- regex从字符串中精确计算值
- 如何计算字符串集合(0.5000个元素)的哈希代码
- Javascript将从Flask发送的字符串计算为整数
- 将变量与 HTML 字符串一起使用,并计算
的数量 - 在 JavaScript 中给定时区字符串的情况下计算 UTC 偏移量
- jQuery/Javascript拆分字符串计算
- 字符串计算的小数
- 从JSON日期字符串计算日期差异
- Javascript字符串计算从PHP变量包含数学表达式(但实际上是一个日期)