假设我们有一个字符串 '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,此时退出循环,返回计数器的值。

JavaScript 统计字符串出现次数:高效代码解析

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

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