Victory! How to filter to just my name?


#1


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


"Your name hasn't been found!" / Being shown multiple times in the console.

I think I did the right thing here, but the message is being displayed a lot of times. How do I make it show up only once? In this case, my name should be found. So why is it displaying the text in the first place?


/*jshint multistr:true */
var text = "Hello, my name is Frank. Frank is born in the Netherlands. Frank wants to be a developer!";
var myName = "Frank";
var hits = [];

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

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

else {
    console.log(hits);   
}


#2

Bear in mind that j is only one letter at a time, so will never equal to myName.

Complicated structure that may be simplified...

}
else if ( ... ) {

}

We have a number of different apporaches to draw upon. Trouble is this project comes a little early in the track and we don't have exposure to all the tools available. I often recommend learners bookmark this part of the project and continue in the track (same thing as RPS project). Once we complete the track we have most of the tools in our kit, and with some reading we will have padded that with others that are not mentioned here.

One such tool is haystack.indexOf(needle, startIndex), which you may have seen in your travels. This String method will return one of, the index of the first occurrence found of needle in haystack, or -1 if not found.

Without modifying the existing code, which should run as expected, we can add a new array, then populate that array with complete matches found.

var full = []
var pos = text.indexOf(myName, 0);

while (pos > -1) {
    full.push(text.substr(pos, myName.length));
    pos = text.indexOf(myName, pos+myName.length);
}
if (full.length) {
    console.log(full.length + " Matches found.");
    console.log(full)
} else {
    console.log("Full name matches not found.");
}

#3

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