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

时间:2021-12-24 18:25:20
<!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;
}

转载自

博主:十二月出行

原文:https://www.cnblogs.com/wcphahaha/p/9855088.html#4099421