javascript - Loop counter resetting to -1 -
this course project simple search counter word "wrox" in string.
my code:
var mystring = "welcome wrox books. "; mystring = mystring + "the wrox website www.wrox.com. "; mystring = mystring + "visit wrox website today. buying wrox. "; var = 0; var wroxcount = 0; while (i <= mystring.length) { = mystring.indexof("wrox",i); wroxcount++; i++; } it works fine until i decides reset -1 reason. works until doesn't. don't know i'm doing wrong.
string.indexof returns -1 when substring searching not found in string.
so should check against in while condition, instead of i <= mystring.length because if i positive, substring found inside string, index lower length.
i = mystring.indexof('wrox'); while (i > 0) { wroxcount++; = mystring.indexof('wrox', + 1); }
Comments
Post a Comment