Search Text for Your Name


#1

To be clear I do not have any problems with this code, I just want to understand this code more specifically.

1st question is that why do I need to add + i after myName.length in the body of 'for' loop? because logically it will uprise myName from 6 to 7 characters (in my case).

2nd question what is hits.push() doing here? And what is his actual job.

var text = "NO NO NO NO NO NO Israel NO NO NO NO NO";
var myName = "Israel";
var hits = [];

for (var i = 0; i <= text.length; i++) {

    if (text[i] == 'I') {
        for(var x = i; x <= (myName.length + i); x++) {
            hits.push(text[x])
        }
    }
};

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

Thank you,
Israel


#2

1) Consider when the loop should stop and what the corresponding condition expression needs to look like.

2) Push adds an element at the end of an array. google "mdn push" for more details/examples


#3

Thank you for the quick reply!

One more question, are the parentheses of (myName.length +i) necessary in this case?

Thank you


#4

Those parentheses are superfluous.


#5

Some more comments:

You also have some redundant semi-colons, and one that's missing.
The empty line at the start of the first for-loop looks unnecessary.
You're not checking for the first character of the name, you're checking for 'I' which coincidentally has the same value as the first character of the name.
I want spaces between if/for and the following (, or at least be consistent


#6

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