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; }