判断一个字符串中某个字符串出现的次数

时间:2021-09-07 16:02:13   收藏:0   阅读:15

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

原文:https://www.cnblogs.com/taosifan/p/15237577.html

评论(0)
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!