5/7 What am I missing here?


#1

var text = "My name is Peter and Peter is cool as ice.";
var myName = "Peter";
var hits = [];

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

    }

}

}

This loop passed and gave me the green, but it is returning a value of 10. I dont understand why it is returning that value at all....and why did I get the green?


#2

Hi @echo6zero

Your code should be looks like this

var text = "My name is Peter and Peter is cool as ice.";
var myName = "Peter";
var hits = [];

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

console.log(hits);

#3

I disagree with the above solution since any word that starts with a P would be logged.
A much better solution would be to compare each word in the string to your name.
You can do that with text = text.split(' ');, Here is the full working code for my solution.

var text = "bla bla alsldl bla bla alsldl bla bla alsldl Emu\
bla bla alsldl Eric bla bla alsldl Eric ";

text = text.split(' ');

var myName = "Eric";
var hits = 0;

for(x = 0; x < text.length; x++){
   if(text[x] == myName){
       hits += 1;
   }
}
console.log(hits);