代码如下:
<!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,start</p>
<button onclick="fun()">Click on it</button>
<p id="demo"></p>
<script>
function fun(){
var str = document.getElementById("p1").innerHTML;
var a=str.indexOf("start");
var num=0;
while(a!==-1){
a=str.indexOf("start",a+1);/*查找字符串中的start从第a+1开始查找并且赋值给a*/
num++;
}
document.getElementById("demo").innerHTML = num;
}
</script>
</body>
</html>