6. Log it! incorrect result in Result tab


#1


Well, exercise is done, no errors, but it shows an incorrect result.

Exactly this:

[ 'M', 'y', ' ', 'n', 'a', 'M', 'u', 'n', 'k', 'a', 'M', 'u', 'n', 'k', 'a' ]

what is wrong with my code, any ideas? :slight_smile:

link to the EXACT exercise:

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


var text = "Hey, how are you \
doing? My name is Munka. Bla bla bla bla bla \
bla bla bla Munka, bla bla bla.";

var myName = "Munka";

var hits = [];


for (var i = 0; i < text.length; i++) {
    if (text[i] === "M") {
      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 code is correct.

You search for M and your code find a M :slight_smile:

"My name is" now we log the 5 next chars "M y whitespace n a"

Everthing is fine you only found a bug in our search :smiley:


#3

I thought so, thanks :blush:


#4

HI like @codmakr said you code is correct and it's the uppercase to My name which gave you that results but you could fixe it like that

if (text[i] === myName[0] && text[i + 1] === myName[1])

.. if text[i] match to the first letter of your name and text[i + 1] match to the second letter of your name.
Hope that could help you.


#5

Thank you, it helped :slight_smile:

"&&" means "and at the same time" in JavaScript?

lets say what could I do if I don't want to write "...&& text[i + n] === myName[n])" for every other letter in myName just to be sure? :slight_smile: Is there some solution?


#6

you could find another one in that discussion


#7

Hey, I just tried this way to make sure it only prints my name and nothing else.

/*jshint multistr:true */
var text = "Hey I just met you, Darrel and this is crazy\
but here's Daniel my number, Daniel so call me maybe";

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

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


#8

With this it is not necessary to concatenate single letters :slight_smile:
And your name is changeable without changing the code.

var text = "Hey, how are you \
doing? My name is Munka. Bla bla bla bla bla \
bla bla bla Munka, bla bla bla.";

var myName = "Munka";

var hits = [];


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

Maybe someone would help that