Stuck here not sure whats the problem?


Cant quite figure out what the problem is? It in Your second "for" loop.

/*Loops and arrays */
var text = "Gary is my name I do get called Fitzy , but I prefer Gary";
var myName = "Gary";
var hits=[];
// We enter the text string loop
for(var i = 0; i < text.length; i++){
// If we locate the first character in our name we begin further iterations

for(var j = 0; j < myName.length; j++){


Hi, Gary.

Your second for loop is missing some fundamental logic in this scenario.

The second for loop should push out the name 'Gary' to hits[] when the if statement before it is equal to true. And for that to happen you need to first come up with a variable (j in this case) and store the index that i is on.i serves as the anchor or location that we entered the second loop from.

So j on the first iteration will be equal to i. The second for loop will fire as long as j is not longer than i + myName.length. Remember i is our anchor, so it shouldn't change. It serves as a good way for us to test whetherj is longer than the index we found 'G' + the length of the name we're trying to find. If it is longer then we should have extracted the name and there is no need to continue iterating.

Hope that helps. But if not feel free to visit this link where I went over this example in some detail.


Hey garyfalkland try this code below

var text = 'Gary is my name I do get called Fitzy , but I prefer Garye';
var myName = 'Gary';
var hits = [];

for(var i = 0; i < myName.length; i++){
    if(myName[i]=== "G") {
       for( var j = i; j < i+myName.length; j++ ) {


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.