'Search text for your Name' Exercise is not accurate


#1

Hello,

I'm not sure if you've already informed about it like 1000 times, but the code demonstrated in this exercise
is not only for finding your name but also for finding every word in the text starting with the first letter.

You should either inform in the description that this code is specifically for text which doesn't contain a word starting with the same letter, or you change the code so it finds the Name exclusively.
It can be like the following:

/*jshint multistr:true */
var text = "One day I was walking down the Itay street \
Then I found an Irish cat Itay running down the street like \
a psycho Itay";
var myName = "Itay";
var hits = [];

for (var i = 0 ; i < text.length ; ++i)
{
    // searching for the whole name using substring //
    if (text.substring(i,i + 4) === myName)
    {
        
        for (var j = i ; j < (myName.length + i) ; ++j)
        {
            hits.push(text[j]);
            }
        }
    }
    
    if (hits.length === 0)
    {
        console.log("Name wasn't found!");
        }
        else 
        {
            console.log(hits);
            }

Best regards,
Itay.


#2

1 suggestion
(text.substring(i,i + myName.length) === myName)


#3

They did mention it somehow. But not in a very clear way.
https://www.codecademy.com/en/courses/javascript-beginner-en-XEDZA/0/7

Copied:

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:

['E','r','i','c','E','d','d','i','e'];

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!

This code really save all the troubles
if (text.substring(i,i + myName.length) === myName)

I was so fixated on trying to use if (text[i] === myName[0]) and didn't really put thoughts on the above option where we learnt .substring() first.

I think it's really clever @eizzo77, if you would like to see my embarrassing incomplete answer (the topic closed before I can get to finish it)

Thanks for sharing your answer! Much appreciated :smile: :smile:


#4

@leonhard.wettengmx.n oh yeah that's what I meant, thank you.

@codexthon Oh, I guess I've missed that one ;D
you're welcome! feel free to ask whatever you like.


#5

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