5/7 & 6/7 - console is printing 800+ characters


#1

My code is included below, the console prints out the first 4 characters of my text, then starts at 0+1 and prints out those four characters, then 0+2 and so on.

I have attempted to change the if statement that triggers the pushing of characters into the hits-array, but it seems to run the if-statement no matter what I do. Examples have been if (text[i] === "H"), if (text[i] === 'H'), if (text[i] === myName[0]).

/*jshint multistr:true */

var text = "My name is Hans and I am currently working \
on learning how to code, build a computer, make money \
to cover my Hans related expenses, and also to ensure that \
Hans is a name that is mentioned a few times in this text.";

var myName = "Hans";

var hits = [];

for (i=0; i < text.length; i++)
{
 if (text[i] === myName[0]);
 {
    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);
}

#2

This code:

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

will be treated by interpreter exactly in the same way as:

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

Why? Because semicolon after if simply terminates conditional part and code in the block is executed no matter if a condition is true or false.


#3

Thank you so much for your help factoradic. That had been bothering me greatly for hours, I really appreciate you taking the time to give me feedback on my code.


#4

You are very welcome :panda_face: Good luck with next exercises!