JavaScript find the position and number of occurrences of a given character in a string

Claim:

Given a string oabcoefoxyozzopp, it is required to output othe position and number of occurrences of the character .

Realization ideas:

  1. Find the first ooccurrence
  2. Then as long as the indexOfreturned result is judged , if it is not -1, then continue to search
  3. Because indexOfonly the first one can be found, the subsequent search uses the second parameter to add 1, to the current index str.indexOf('o', index + 1), to continue the search

Code:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        var str = "oabcoefoxyozzopp";
        var index = str.indexOf('o');
        // 先找到第一个o的位置,幅值给index
        var num = 0;
        // num表示o出现的次数
        while (index !== -1) {
     
     
            // 如果index不等于-1表示还没查找完,则继续查找
            // 若index等于-1,则表示当前索位置之后没有o了,退出循环
            console.log(index);
            // 输出当前的位置
            num++;
            index = str.indexOf('o', index + 1);
            // 在当前的索引位置+1,重新赋值给index,从后一个位置继续查找
        }
        console.log('“o”出现的次数是: ' + num);
    </script>
</body>

</html>

Output result:

Insert picture description here

Guess you like

Origin blog.csdn.net/Jack_lzx/article/details/109262977