Issue with my search text for your name program


#1


https://www.codecademy.com/courses/javascript-beginner-en-XEDZA/0/7?curriculum_id=506324b3a7dffd00020bf661


It returns [ 'I', 'f', ' ', 't' ] instead of my name or anything beginning with "L" (including the square brackets). Another Note is that the program when run is successful and asks me to continue to the next lesson. Please help, Thanks.


var text = "If the memes is equal to Luke's dreams should he follow \
his dreams or should Luke give up and not be the meme lord \
he was born to be";

var myName = "Luke";

var hits = [];

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

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


#2

Your first for loop should search text.length cause its a nested for loop :stuck_out_tongue:


#3

This had the exact same outcome.


#4

I did it like this:

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

In the first for loop I am irritating through text.length if the index text[i] === "N", second loop irritates the same as my loop but isn't pushing the index of j into my array but index of i.


#5

when i changed it to

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

i get the outcome as [ "I", "I", "I", "I" ] (including the square brackets) so a change but still not working...


#6

in your first if statement in your first for loop the text[i] should be equal to "L"


#7

Okay Thanks

At first i changed the if statement to this

if (text[i] === "L") {

which did change the outcome to ["L", "L", "L", "L"]
Then i changed the hits.push back to j instead of i

hits.push(text[j]);

And now i am getting the correct outcome of ["L", "U", "K", "E", "L", "U", "K", "E"] So Thanks Heaps for all your help :slight_smile:


#8

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