JS 统计字符出现次数

261 阅读1分钟

涉及知识

indexOf()

语法:字符串.indexOf(字符)
字符串.indexOf(字符,开始索引)
返回值:该字符字原始字符串内的索引位置, 如果你检索的是字符串片段, 那么是开头字符的索引位置

实现思想

do-while实现检索从字符串0开始,并通过count记录目标字符出现次数

功能实现

<script>
        String.prototype.count_str = function count_str(target_str) {
            var positon = -1 //索引位置
            var count = 0 //记录出现次数
            do {
                same = this.indexOf(target_str, positon + 1)
                if (positon != -1) { //出现一次就记录一次
                    count++
                }
            } while (positon != -1)
            return count
        }
        var str = "我的我的我的掘金"
        console.log(str.count_str("的"))//3
    </script>