006-统计某一字符或字符串在另一个字符串中出现的次数
知识点:
- 正则匹配
- 对匹配的字符串替换为空,接着进行下一轮循环匹配
// 方法一
function strCount (str, target) {
let count = 0;
if (!target) return count;
while (str.match(target)) {
str = str.replace(target, '');
count++;
}
return count;
}
// 方法二
function substrCount (str, target) {
if (Object.prototype.toString.call(str).slice(8, -1) === 'String' && !str) {
alert("请填写字符串");
} else {
return (str.match(new RegExp(target, 'g')).length);
}
}
console.log('统计字符次数', strCount('abcdfg abfds abcgh abcc', 'abc')) // 3 次