假设我们有一个字符串str,我们要统计其中某个子字符串sub出现的次数,可以使用以下代码:

function countSubstring(str, sub) {
  var count = 0;
  var index = 0;
  while (true) {
    index = str.indexOf(sub, index);
    if (index === -1) {
      break;
    }
    count++;
    index += sub.length;
  }
  return count;
}

// 示例
var str = "hello world, hello javascript!";
var sub = "hello";
var count = countSubstring(str, sub);
console.log("字符串\"" + sub + "\"出现了" + count + "次");

其中,我们使用了String的indexOf方法来查找子字符串在主字符串中的位置,如果找到了,则计数器加1,然后将查找位置移动到上一次查找的位置加上子字符串长度的位置,继续查找下一个子字符串出现的位置。如果查找到了主字符串末尾,indexOf方法会返回-1,此时退出循环,返回计数器的值。

用js生成一个统计字符串出现次数

原文地址: http://www.cveoy.top/t/topic/3Sl 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录