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', '.') );
indexOf usage
count++; offset += subStr.length;
count
represents a counter, recording the number of times a character appearsoffset
is assigned to the second parameter ofindexOf
, which represents the value from the parent string Start searching for the substringsubStr
when
offset
is found, justcount
+1, and then start searching from the position ofoffset += subStr.length
, becauseindexOf
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