I am stuck need help


#1

Need help with exercise 5.your second for loop in javascript

second for loop should stop when it reaches its current point in the string+myName.length

Oops, try again. Careful: your second 'for' loop should stop when it reaches its current point in the string + myName.length

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

#2

Hi,

The following:

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

should probably be:

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

Do you know why? :wink:


#3

Let's look at what the error says:

Oops, try again.
Careful: your second 'for' loop should stop when it reaches its current point in the string + myName.length.

The loop should stop when you reach the current point in the string (which is i) + myname.length. Let's try to adapt this part of the code:
for(var j=i;j<i + myName.length;j++)

Ok. Now the error is gone, but we get a new error:

Oops, try again.
It looks like your second 'for' loop isn't pushing values to the
hits array. Make sure it's working properly and that myName's text
appears somewhere in the text variable.

The loop isn't pushing values. When should it pass values? When the first letter of the name is equal to the current letter in the text. You're checking this with text[i] === 'N', while it should work more generally, like this (try to think of it yourself first) text[i] === myName[0].

But we're still getting the error. In this case, the problem is not in your code exactly, but in the choice of your string. It's logical that there won't be anything pushed, because the first letter 'N' isn't even in the text. Try changing the name (or the text) to something else, and it will work.