6. Log it


#1



Hey all, When I run this code, the array is returns is
"[ 'R',
'o',
'b',
'e',
'r',
't',
'o',
'R',
'o',
'b',
'e',
'r',
't',
'.',
'R',
'o',
'b',
'e',
'r',
't',
'o',
'R',
'o',
'b',
',',
' ',
'o',
'r',
'R',
'o',
'b',
'e',
'r',
't',
'.',
'R',
'o',
'b',
'e',
'r',
't',
'.' ]

Any idea why it isnt returning JUST the Roberto's?

var text="hi my name is Roberto, not Robert. Please only call me Roberto or Rob, or Berto, but not Robert. I hate Robert."
var myName="Roberto"
var hits=[];
for(var i = 0; i < text.length; i++){
if(text[i] === "R"){
for(var j = i; j < (i + myName.length); j++){
hits.push(text[j]);
        }
    }
}
if (hits.length === 0) {
    console.log("None found!");
} else {
    console.log(hits);
}


#2

Ah, I just realized that the point of the exercise was NOT to pull only exact matches. That makes more sense.

Anyone have any ideas how one would ONLY pull exact matches?

Thanks!


#3

you could build another loop to validate it is indeed your name?

if(text[i] === myName[0]){
   yourName = true;
   for (var k = 1; k < myName.length; k++){
       if(text[i + k] != myName[k]){
            yourName = false; 
            break;
      }
   }
}

then build an if condition around the for loop that pushes the hits into your array:

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

#4

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