计算图案在字符串中出现的次数

Counting the number of times a pattern appears in a string

本文关键字:字符串 计算      更新时间:2023-09-26

使用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