<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>查询字符串次数</title>
</head>
<body>
<button onclick="myFunction()">点击查询字符串中"first"字符出现的次数</button>
<p id="demo"></p>
<script type="text/javascript">
function myFunction()
{
var str = "first,second,third,first,speed,first,flexible,first,third";
var count=0;
var index=0;
var key="first";
while((index = str.indexOf(key,index))!= -1)
{
index += key.length;
count = count+1;
}
document.getElementById("demo").innerHTML = count;
}
</script>
</body>
</html>
注:本文借鉴自https://www.cnblogs.com/yyh187/p/9835689.html