如何修改count()函数以实现指定字符串出现次数统计功能?
实现统计文本中目标字符串出现次数的
count_occurence函数 步骤1:获取目标文本
先从id为randomtxt的div中提取文本内容:
const text = document.getElementById('randomtxt').textContent.trim();
步骤2:实现count_occurence函数
以下两种实现方式都能满足你的需求,可根据场景选择:
方式一:循环查找法(直观无正则依赖)
逻辑清晰,不需要处理正则特殊字符,适合普通字符串统计场景:
function count_occurence(text, target) { let count = 0; let currentIndex = text.indexOf(target); while (currentIndex !== -1) { count++; // 从当前匹配位置的下一个字符开始继续查找,避免重复匹配同一位置 currentIndex = text.indexOf(target, currentIndex + target.length); } return count; }
方式二:正则表达式法(简洁高效)
如果需要扩展匹配规则(比如不区分大小写),可以用这种方式,同时要转义目标字符串中的正则特殊字符:
function count_occurence(text, target) { // 转义正则特殊字符,避免目标字符串中的特殊符号干扰匹配 const escapedTarget = target.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // 创建全局匹配正则,如需不区分大小写可添加'i'标志(比如'gi') const matchRegex = new RegExp(escapedTarget, 'g'); // 匹配所有结果并返回数量,无匹配时返回0 const matches = text.match(matchRegex); return matches ? matches.length : 0; }
测试验证
调用函数即可得到期望结果:
console.log(count_occurence(text, "the")); // 返回20 console.log(count_occurence(text, "of")); // 返回9 console.log(count_occurence(text, "from")); // 返回3
内容的提问来源于stack exchange,提问作者user18456359
相关产品推荐
相关产品推荐

