0

This is a course project for a simple search counter for the word "Wrox" in a string.

My code:

var myString = "Welcome to Wrox books. ";
myString = myString + "The Wrox website is www.wrox.com. ";
mystring = myString + "Visit the Wrox website today. Thanks for buying Wrox. ";

var i = 0;
var wroxCount = 0;

while (i <= myString.length) {
    i = myString.indexOf("Wrox",i); 
    wroxCount++;  
    i++;
}

It works fine until i decides to reset to -1 for some reason. It works until it suddenly doesn't. I don't know what I'm doing wrong.

poke
  • 369,085
  • 72
  • 557
  • 602
xa3d
  • 1
  • 1
  • 6
    Because `indexOf` returns `-1` if whatever you're looking for doesn't exist. so once you find the LAST `Wrox` in your string, obviously there's no more Wroxes past that point, and you get -1. so you find wrox #1, #2, ... #n, then you're back to index 0 and scanning the string over and over and over... – Marc B Jul 07 '15 at 19:27

1 Answers1

0

String.indexOf returns -1 when the substring you are searching for was not found in the string.

So this is what you should check against in your while condition, instead of i <= myString.length because if i is positive, the substring was found inside the string, so the index is lower than the length.

i = myString.indexOf('Wrox');
while (i > 0) {
    wroxCount++;
    i = myString.indexOf('Wrox', i + 1);
}
poke
  • 369,085
  • 72
  • 557
  • 602
  • I didn't know that. Thanks so much! – xa3d Jul 07 '15 at 19:31
  • 1
    @xa3d You’re welcome! Please remember to upvote helpful answers and ultimately [accept the answer](http://meta.stackexchange.com/a/5235/141542) that solved your problem to mark your questions as resolved. Both here and on [your other question](http://stackoverflow.com/questions/30791009/why-am-i-pulling-an-error-array-push-course-work). Thanks :) – poke Jul 07 '15 at 19:51