Problems with the "search text for your name" exercise


#1

Hi, I'm having trouble with the result of the console.log on this exercisce, my code is:

var text = "I am David son of David father of David uncle of David nephew of David grandson of David cousin of David";
var myName = "David";
var hits = [];

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

if (hits === 0) {
console.log("Your name wasn't found!");
}

else {
console.log (hits);
}

And the result i get is something like this:

[ 'D',
'a',
'v',
'i',
'd',
' ',
's',
'o',
'n',
' ',
'o',
'f',
' ',
'D',
'a',
'v',
'i',
'd',
' ',
'f',
'a',
't',
'h',
'e',
'r',
' ',
'o',
'f',
' ',
'D',
'a',
'v',
'i',
'd',
' ',
'u',
'n',
'c',
'l',
'e',
' ',
'o',
'f',
' ',
'D',
'a',
'v',
'i',
'd',
' ',
'D',
'a',
'v',
'i',
'd',
' ',
'f',
'a',
't',
'h',
'e',
'r',
' ',
'o',
'f',
' ',
'D',
'a',
'v',
'i',
'd',
' ',
'u',
'n',
'c',
'l',
'e',
' ',
'o',
'f',
' ',
'D',
'a',
'v',
'i',
'd',
' ',
'n',
'e',
'p',
'h',
'e',
'w',
' ',
'o',
'f',
' ',
'D',
'a',
'v',
'i',
'd',
' ',
'g',
'r',
'a',
'n',
'd',
's',
'o',
'n',
' ',
'o',
'f',
' ',
'D',
'a',
'v',
'i',
'd',
' ',
'c',
'o',
'u',
's',
'i',
'n',
' ',
'o',
'f',
' ',
'D',
'a',
'v',
'i',
'd',
undefined,
undefined,
undefined,
undefined,
...]

this goes on and on and I cant seem to understrand where I went wrong, also I have a doubt as to what var hits = [] and (text[j]) do.

Thank you all in advance!


#2

there is a problem with your syntax here:

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

[i] should be i.

The moment encounter a hit (aka, the if statement is true), you use the second for loop to loop over hits (D,a,v,i,d) one by one, you need to store the hits somewhere, you create an array called hits to store them:

var hits = [];

now, j holds the index where your name is, so text[j] will convert this index into a actual letter


#3

Solved! I changed the for loop to for ( var j = i; j < (myname.length + i); j++) :slight_smile:
So what .push does is it sends the hits to the empty hits variable am I right?

Thank you!


#4

yea, you are right. Except i would put it this way: push will append the item (hit) to hits array/list.

But we mean the same thing