统计字符出现的次数

Posted on 2018-11-25 21:42  mini7  阅读(139)  评论(0编辑  收藏  举报
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="./index.css">
    <title>js学习</title>
</head>
<body>
    <p id="p1">start,stop,speed,start,speed ,velocicty,start</p>
    <button onclick="fun()">Try it</button>
    <p id="demo"></p>
    <script src="./index.js"></script>
</body>
</html>



function fun(){
    var str = document.getElementById("p1").innerHTML;
    var num=0;
    var a=str.indexOf("start");
    while(a!==-1){
        a=str.indexOf("start",a+1);
        num++;
    }
    document.getElementById("demo").innerHTML = num;
}