使用RegExp

function getCharCount(str, char) { //str父字符串,char子字符串
  const regexp = new RegExp(char, 'g') //'g'表示需要匹配整个字符串
  const result = str.match(regexp) //match方法匹配字符串并放回一个由n个char组成的数组,n = char出现的次数,如果没有找到就返回null
  const count = result ? result.length : 0;
  return count;
}