5/7 Syntax Error


#1

var text = "My name is Joe, nice to meet you, Joe."
var myName = "Joe"
var hits = []
for (var i = 0; i < text.length; i++)
{
if (text[i] == 'J'){
for (var j = i < (myName.length+i);j++
hits.push(text[j]);
}
}
Please Help!


#2

This chapter is a bit trickier than anything earlier.

There are a couple of problems with your code. Here's code that works:

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

First, in your if statement, you should use the triple equal sign.

Second, in the test component of the for loop, you need to subtract 1 from the "myName.length + i" because all arrays are zero-based.

Hope this helps.


#3

A cleaner version of the for statement


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

and push i not j :smile:


#4

Hi howardsilverdeer_com,

I tried that and it didn't work for me.

here is my code:

var text = "This is a long string of text \
my name is raphael, i'm suppose to write raphael a few times\
raphael, raphael";

var myName = "raphael";

var hits = []

for (var i = 0; i < text.length; i++){
if (text[i] === myName[0]) {
for (r = i; r <= (i + myName.length - 1; r++){
hits.push(text[r]);
}
}
}

Can someone please help me figure out what I did wrong? Thank you!


#5

I just tried this and I got "42" as an answer, I'm not sure why or what that even means? I thought we're suppose to get our name printed out? Can someone please explain. I don't know why it passed when the result doesn't make sense?

var text = "This is a long string of text \
my name is raphael, i'm suppose to write raphael a few times\
raphael, raphael";

var myName = "raphael";

var hits = []

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


#6

Close off the array

var hits =[];

Even I had difficulty with this exercise,
Check out my question!


#7

var myName = Someones Name; // 'Someones Name' is 13 characters, that's counting the space also.

for(var j = i; j < (myName.length + i); j++) { // 'someones name' starts with (s)

hits.push(Someones Name [s]); // Make sure to define 'Someones Name!

// This code will work, after some debugging