Code only displays empty array. HELP!


#1

var text = "turtles turtles joseph turtles joseph turtles"
var myName = "joseph"
var hits = []

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

if(hits.length = 0) {
console.log("Your name wasnt found")
}
else {
console.log(hits)
}

This then just logs [] to the console.

Help please!


#2

Hi @josephsemmens

Your if condition

if(hits.length = 0)

Must be change to

if(hits.length === 0)

Hold on :wink:


#3

text = "Blah blah blah blah blah blah Eric \
blah blah blah Eric blah blah Eric blah blah \
blah blah blah blah blah Eric";

var myName = "Eric";
var hits = [];

// Look for "E" in the text
for(var i = 0; i < text.length; i++) {
	if (text[i] === "E") {
		// If we find it, add characters up to
		// the length of my name to the array
		for(var j = i; j < (myName.length + i); j++) {
			hits.push(text[j]);
		};
	};
};

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

this is the right code