javascript - Regarding the statistics of the number of times a certain character appears in a string, I saw a piece of code online and there is a part in it that I don't understand what it means.
迷茫
迷茫 2017-06-12 09:33:03
0
1
1016

Today I used the split() method to count the number of times a certain character appears in a string. I also checked Baidu to see if there are other methods. I saw the following function, but count ; offset = subStr.length; I don’t understand what it means. Please ask the seniors passing by to clarify!

function countInstances (mainStr, subStr) {
    var count = 0;
    var offset = 0;
    do{
        offset = mainStr.indexOf(subStr, offset); // 通过indexOf获得某字符在字符串中出现的位置
        if( offset != -1 ) { // 如果某字符存在于字符串中
            count++;
            offset += subStr.length;
        }
    } while ( offset != -1 );
    return count;
}
countInstances('www.segmentfault.com', '.')
// alert( countInstances('www.segmentfault.com', '.') );
迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

reply all(1)
typecho

indexOf usage
count++; offset += subStr.length;
count represents a counter, recording the number of times a character appears
offset is assigned to the second parameter of indexOf, which represents the value from the parent string Start searching for the substring subStr
when offset is found, just count+1, and then start searching from the position of offset += subStr.length, because indexOf can only determine the initial Find the index of the substring. .
I seem to say it’s complicated, but it’s actually very simple. Just draw the execution process on paper and you’ll understand

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template