Is there a way to shorten this code down


#1

Is there a way to shorten this code down? Just curious. I made it so I wouldn't get false +s w/ similar words but I imagine there is a way to cut this down.

/*jshint multistr:true */

var text = "My name is Andrew. I am named after St.Andrew and my name is Andrea.";
var myName = "Andrew";
var hits = [ ];

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

Hi @silverpixel25,

It took me some time to digest this. It's perhaps the first time I am seeing so much nesting. So hats off to you for having the patience of writing this :smiley:

Now, back to the question. Hint: There's a linear pattern in these if blocks' conditions:

 if (text[i] === myName[0])   {
        if (text[i+1] === myName[1])   {
            if (text[i+2] === myName[2])   {
                if (text[i+3] === myName[3])   {
                    if (text[i+4] === myName[4])   {
                        if (text[i+5] === myName[5])   {

Don't you think a for loop fits the purpose here? :wink: