What am I doing wrong?


#1

/*jshint multistr:true */

var text = "text text text text text text Karen text text text text text text";
var myName = "Karen";
var hits = [];

for(var i = 0; i < text.length; i++) {
if (text[i] === 'K') {
for(var j = i; i <= myName.length; i ++) {

        newArray.push('Karen')

    }
}

}

Oops, try again. Careful: your second 'for' loop should stop when it reaches its current point in the string + myName.length.


#2

@programmeranonymous,

= I ===============================================

In the first for-loop you are running over the text

  1. character by character using text[i] as character-value, as long as text.length
    comparing it to "K" in a IF-statement

  2. then in the second for-loop you preserve the i-variable by making the j-variable to work with.

    • now using j you want to go over the text from position i upontill i + nameLength
    • so you have to change the condition of the second for-loop to
      j < i + nameLength (and do not use the less-equal-operator)

= II ============================================

With

var hits = [];

you have created an empty Array.
It is into this hits Array you want to push-in every character
of the =text= which is in between j < i + nameLength
using an Array-prototype-Method push()
by using the code

hits.push( text[j] );

= III ===========================================

Then at the end you might want to see the result of the hits-array
console.log( hits );

= IV ===========================================

References:

google search
javascript push array site:developer.mozilla.org
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push

javascript push array site:stackoverflow.com
= http://stackoverflow.com/questions/351409/appending-to-array

www.crockford.com
http://javascript.crockford.com/survey.html
http://javascript.crockford.com/code.html


#3

Like this?

/*jshint multistr:true */

var text = "text text text text text text Karen text text text text text text";
var myName = "Karen";
var hits = [];

for(var i = 0; i < text.length; i++) {
if (text[i] === 'K') {
for(var i + nameLength; j < i + nameLength; i ++) {

        hits.push( text[j] );

    }
}

}

console.log( hits );

Oops, try again. There was a problem with your syntax.


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

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for