1. 程式人生 > >JS-使用indexof來統計字元出現次數

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

轉載自

博主:十二月出行

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