0

I am a newbie to javascript and made a mistake somewhere with the following code to find the string "Craig" and push it into a new array "Hits".

var text = "Hey, how are you \ doing? My name is Emily.\ My other friends       name is Craig. My friend Craig is learning JavaScript";
var myName = "Craig"
var hits = [];

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

2 Answers 2

1

Your for loop condition is not correct. Replace it with below. Use j < i + myName.length

for(var j = i; j < i+myName.length; j++ )

PS:- There are better way to do this, indexOf().

Sign up to request clarification or add additional context in comments.

Comments

0
var text = "Hey, how are you \ doing? My name is Emily.\ My other    friends name is Craig. My friend Craig is learning JavaScript";

    var myName = "Craig"
    var hits = [];

    if (str.indexOf("Craig") > -1)
    {
       hits.push(myName);
    }

Here indexOf will return the position of the string match,if string is not found then the indexOf returns -1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.