7/7 A loop to count the remaining letters of myName? Does that even work in theory?


#1

Hello! So I am trying to build a loop in order for the script to be able to search not just for the first letter of my name, but also all the other ones.

/*jshint multistr:true */

var text = "What is this? Aaron, have you seen this? Aaron? Where are you? / Ah, shit! Aaron you scared me! Asshole!";

var myName = "Aaron";

var hits = [];

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

// So this was my idea of creating a loop that would look for the other letters of my name, because I am too lazy to type the number everytime like this: "if (text[ i + x ] === myName[ x ] &&& text[ i + x1] === myName[ x1 ]" and so on. (below)

// I created this...

var count = [];

for (var y = 0; y < myName.length; y++) {
    count.push(y);
};

// ...in order to put the numbers of "count[y]" into what formerly has been just searching for the first letter of myName. So I just inserted count.push(y) into what formerly has been number 0, or well you know the first letter of "myName".

if (text[i + count.push(y)] === myName[count.push(y)]) {
    
    for (var j = i; j < (i + myName.length); j++) {
        hits.push(text[j]);
    }
}

};

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

else {
console.log(hits);
};

// And the result of this is following:

[ 's',
'h',
'o',
'l',
'e',
'h',
'o',
'l',
'e',
'!',
'o',
'l',
'e',
'!',
undefined,
'l',
'e',
'!',
undefined,
undefined,
'e',
'!',
undefined,
undefined,
undefined,
'!',
undefined,
undefined,
undefined,
undefined ]


#2

Maybe
https://www.codecademy.com/forum_questions/546e79b852f863fbe50001f7