Indexof

用indexof查找一串字符中某个字符出现的次数:

<!DOCTYPE html>
<html>
 <head>
     <meta charset="utf-8">
        <title>Indexof</title>   
    </head>
    <body>
     <button onclick="myFunction()">点我可查看这一串"one,two,three,one,one,two,three"字符中"one"字符出现的次数</button>   
        <p id="demo"></p>
        <script type="text/javascript">
         function myFunction(){
             var str = "one,two,three,one,one,two,three";
                var count=0;
                var index=0;
                var key="one";
                while((index = str.indexOf(key,index))!= -1){
                 index += key.length;
                    count = count+1;
                }
                document.getElementById("demo").innerHTML = count;
            }
        </script>   
    </body>
</html>

猜你喜欢

转载自www.cnblogs.com/X1604389100/p/9887095.html