You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaScript中统计字符串中子字符串的出现次数?

如何在JavaScript中统计子字符串的出现次数(支持含空格的子串)

需求示例

需要实现一个函数,统计指定子字符串在目标字符串中的出现次数,子串可包含空格:

countOccurrences('the quick brown fox jumps over the lazy dog.', 'the')
// 输出: 2

countOccurrences('the quick brown fox jumps over the lazy dog.', 'the quick')
// 输出: 1

方法1:使用indexOf循环查找

这种方法简单直接,天然支持含空格的子串,还能灵活控制是否允许重叠匹配:

function countOccurrences(str, substr) {
  let count = 0;
  let startIndex = 0;
  const substrLen = substr.length;

  // 处理空串输入的边界情况
  if (substrLen === 0) return 0;

  // 循环查找直到找不到匹配项
  while ((startIndex = str.indexOf(substr, startIndex)) !== -1) {
    count++;
    // 移动到当前匹配的末尾,避免重叠匹配
    // 若需统计重叠匹配,改为 startIndex += 1
    startIndex += substrLen;
  }

  return count;
}

// 测试
console.log(countOccurrences('the quick brown fox jumps over the lazy dog.', 'the')); // 2
console.log(countOccurrences('the quick brown fox jumps over the lazy dog.', 'the quick')); // 1

方法2:使用正则表达式

适合需要更复杂匹配规则的场景,注意要先转义子串中的正则特殊字符:

// 转义正则表达式中的特殊字符(如 . * + ? 等)
function escapeRegExp(str) {
  return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}

function countOccurrences(str, substr) {
  if (substr.length === 0) return 0;
  
  // 创建全局匹配的正则,支持含空格的子串
  const regex = new RegExp(escapeRegExp(substr), 'g');
  const matches = str.match(regex);
  
  // 存在匹配项则返回数量,否则返回0
  return matches ? matches.length : 0;
}

// 测试
console.log(countOccurrences('the quick brown fox jumps over the lazy dog.', 'the')); // 2
console.log(countOccurrences('the quick brown fox jumps over the lazy dog.', 'the quick')); // 1

额外说明

  • 区分大小写:如果需要不区分大小写的匹配,将正则的标志改为'gi'即可;
  • 重叠匹配:若要统计重叠的子串(比如countOccurrences('aaaa', 'aa')期望得到3),方法1中把startIndex += substrLen改为startIndex += 1,方法2则使用正向预查正则:new RegExp((?=${escapeRegExp(substr)}), 'g'),再取匹配结果的长度。

内容的提问来源于stack exchange,提问作者CuteMrMerp

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 19:02:15