7/7: Can't convert hits array to string - please help!


#1

I'm having trouble converting my hits array to a string - I've tried the .toString() method as well as the .join("") method. Still not working, not sure what I'm doing wrong. I'm sure it's something tiny.

Additionally, the challenge told me to write something that had my name in it more than once. Am I supposed to stop the loop once it finds it the first time? Because now I have an array with my name in it twice.

var text = "Hello, my name is Kelsey. Not \ Chelsea.  Kelsey.";
var myName = "Kelsey";
var hits = [];

for (var i = 0; i < text.length; i++){
    if (text[i] === "K") {
        for (var j = i; j < i + myName.length; j++) {
           hits.push(text[j]);
        }
    }
}
if (hits === "") {
    console.log("Your name wasn't found!");
} else {
    hits.join("");
    console.log(hits);
}

#2

@kcdilla

Why are you trying to convert your hits array to a string using .toString() method or .join("") method? They didn't teach you how to do it so I don't expect them to trick you by putting one in the exercise. You should add i to myName like this myName + i and surround them with parentheses.
In your if condition, you must calculate the length of hits and test whether hits.length === 0. On your else, remove the hits.join("") because this is not useful. Hope this helped you.


#3

I'm just following the lesson's suggestion:

"Think about how you might fine-tune this program to make sure it only finds exact matches for your name. Search the Internet to see if there are any built-in JavaScript string methods that can help!"

My thinking is that if I convert the array to a string, i can easily check if that string matches the myName string.


#4

I guess your problem is that .join("") and toString() produce values and do not alter the array, so better use:

strigifiedHits = hits.toString()
joinedHits = hits.join("")

Also think about the substr and substring method. Or if you really wanna go advanced google regular expressions (but rather do this later).

@miniapple8888 You're basically right but I guess 7/7 is a free play exercise so the test functions here are probably not that limited to a certain way of solving.