Search text of your name 7/7 codecademy


#1


Now, as we mentioned, this system isn't perfect. For instance, if the paragraph contains both "Eric" and "Eddie", we'll see this in our hits array:

Q: How do I print only one name either Eric or Eddie?


Replace this line with your code. 
var text = "Blah blah blah blah blah blah Eric \
blah blah blah Eddie blah blah Eddie blah blah \
blah blah blah blah blah Eric";

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

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


#2

You could check also for the last letter? using: text[i] + myName.length -1 by nesting another if condition or using and (&&)

you could build another loop to verify all letters?


#3

So after doing the search to find exact names, I found there's a lot of useless code in there for this task.

It can be simplified to:

Replace this line with your code.
var text = "Blah blah blah blah blah blah Eric \
blah blah blah Eddie blah blah Eddie blah blah \
blah blah blah blah blah Eric"

var hits = text.match(/Eric/g);

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

Much simpler.


#4

yes, it is simpler, but it doesn't teach you to build your own algorithms.


#5

Thanks a lot, guys!!!


#6

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