5/7 Help!


#1
/*jshint multistr:true */
var text = "Pete,blah blah blah newcastle blah Pete"
var myName = "Pete"
var hits = []

for (var i = 0; i <= text.length; i++) {
    if (text[i] === "P") {
      for (var j = i; i += myName.length; i++) {
          hits.push(text[j]);
        }
    }
}

Error: Out of memory

No idea what is wrong here!


#2

Ok, played around with it and got this:

/*jshint multistr:true */
var text = "Pete,blah blah blah newcastle blah Pete"
var myName = "Pete"
var hits = []

for (var i = 0; i <= text.length; i++) {
    if (text[i] === "P") {
      for (var j = i; j < myName.length; j++) {
          hits.push(text[j])
        }
    }
}

console.log(hits)

The console now shows [ 'P', 'e', 't', 'e' ] but still does not pass...


#3

Change the condition ot the first loop to:

i < text.length

Change the condition of the second loop to :

j < i + myName.length

And try to push text[i], not j here:


#4

Thanks julietaatanasova! It passed, however, the console showed [ p p p p p p p p ] instead of [ p e t e p e t e ]. Do you know why?


#5

Read carefully the text before the instructions:

This loop will make sure each character of your name gets pushed to the final array. 
The if statement says: "If we find the first letter of the name, start the second for
 loop!" 
This loop says: "I'm going to add characters to the array until I
 hit the length of the user's name." So if your name is 11 letters long,
 your loop should add 11 characters to hits if it ever sees the first letter of 
myName in text.

Maybe there is no problem to add text[j]. The count of the pushed letters is more important to this task.

Your problem was that you was adding once the characters of the name, when you have 2 occurrences of your name in the text.


#6

thanks! Surely though the count of the pushed letters is only useful if it counts from the first occurrence, and then pushes the right number of letters that come afterward, thus giving the full name. Printing pppppppp is just as useless to me as printing p.

In my original code it was finding the first letter, and then printing the correct number of subsequent letters, it just wasn't finding the second instance. i feel like the new code solves that problem but creates another.