Victory Lesson 7 Substring?


#1


https://www.codecademy.com/en/courses/javascript-beginner-en-XEDZA/0/7?curriculum_id=506324b3a7dffd00020bf661


Ok guys Im confused here, should I use a substring method for calling the names one by one? Can someone show me a working example to study? Im completely clueless


var text = "Hey, how are you\
doing? My name is James.\
Can Emma come out to play?\
No you may not james Yanos";
var myName = "James","Yanos"; //Doesnt work with 2 words yet
var hits = [];
//i will ++ till it reaches lengthVal of count
for (i = 0; i < text.length; i++) {
    //console.log(i)
    if (text[i] === "J") {
        console.log(j)
        for (var j = i; j < (i+myName.length); j++  ) {  
            hits.push(text[j]);
        };
    };
};
console.log(hits)


#2

I was thinking something like console.log(text[i].substring(0,i)); but cant think about how to get it to work.

var text = "Hey, how are you\
doing? My name is James.\
Can Emma come out to play?\
No you may not james(Yanos)";
var myName = ["James","Yanos]"; //Doesnt work with 2 words yet
var hits = [];
//i will ++ till it reaches lengthVal of count
//console.log(myName[0].substring(0,1));
for (i = 0; i < text.length; i++) {
    //console.log(i)
    if (text[i] === myName[i].substring(0,i)) {
        console.log(j)
        for (var j = i; j < (i+myName.length); j++  ) {  
            hits.push(text[j]);
        };
    };
};
console.log(hits)

#3

var text = " swqdhkj Eric y y blablabla";
var myName = "Eric"; 
var hits = [];

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

if(hits === []){ console.log("Not found"); }
else{console.log(hits); }

var myName = ["James","Yanos"]; will not work because myName.length will return 2 which is the length of the array.
If you want to search two names or more in the text, you can add another loop for

var text = " swqdhkj Eric y y blablabla ops";
var myName = ["Eric", "swqdhkj"];
var hits = [];

for (var i = 0; i < text.length; i++) {
    //for each name in myName...
    for (var k=0; k < myName.length; k++){
        //if text[i] correspond to the first letter of the current name...
        if (text[i] === myName[k][0]){
            //for each letter near text[i] till the length of the name...
            for (var j = i; j < i+myName[k].length; j++  ) {
              //if the letter is not null push it into hits[]
              if(text[j]){hits.push(text[j]);}
            }
            hits.push(" "); //just for eyes
        }
    }
}
    

if(hits === []){ console.log("Not found"); }
else{console.log(hits); }

But the code is not yet optimal :wink:


#4

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