JS-使用indexof来统计字符出现次数

复制代码
<!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;
}
复制代码
posted @ 2018-10-26 16:02  不要乱起名  阅读(1520)  评论(0编辑  收藏  举报