Your second "for" loop isn't working


#1

I've been examining my code for ages, and looking at the Q/A forum, and I can't find what's wrong. Does anyone notice a mistake in my code?

Here's the most recent attempt:
(The blanks are not part of the original code)

var text = "Some random text. Here's my name once: _______. And now here it is again: _______.";

var myName = "_______";

var hits = [];

for (i = 0; i < text.length; i++)
{
if (text[i] === '_')
{
for(j = i; j < myName.length; j++)
{
hits.push(text[j]);
}
}
}
console.log(hits);


#2

yeah I think the problem is your for loop condition..

you have:

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

If you notice you're setting j to be the same as i, then j < myName.length. this would probably be always less in most cases, unless your name is close in the beginning of the string. This is why it doesn't run, because when it find your name in the string, at that point j is less then myName.length.

You want to change it to
j < ( myName.length + i )
This way you'll capture the whole name from the postion where it found the first letter to the end.


#3

Thank you! Finally, I can continue.