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', '.') );
typecho2017-06-12 09:35:03
indexOf usagecount++; 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