Andrew Graber
Andrew Graber

Reputation: 187

Loop that finds a word in a string

So, i'm working on a 'for' loop that will identify my name, Andrew, and push it into an array, but there's something wrong with it

/*jshint multistr:true */

var text = ("Andrew is really awesome and Andrew should be working on the project, but there is honestly nothing for Andrew to do.");
var myName = ("Andrew");
var hits = [];
for (var i = 0; i < text.length; i ++) {
    if (text[i] === "A") {
        for (var j = i; i + nyName.length; i ++) {
            hits.push(text[j]);
        }
    }
}

Also, the second loop is supposed to stop when it reaches the end of myName.

Upvotes: 0

Views: 118

Answers (4)

Bart
Bart

Reputation: 17361

The misspelled myName isn't the only part that fails. You for loop will never end the loop because i + myName.length will always evaluate to true. You also need to increase the value of j or it will always get the character at index i.

Here's the corrected loop.

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

Upvotes: 0

grasp
grasp

Reputation: 68

You're using JSHINT, so just read the error messages and it'll tell you exactly what's wrong.

Errors:

  • Line 7: for (var j = i; i + nyName.length; i ++) {

    'nyName' is not defined.

  • Line 3: var myName = ("Andrew");

    'myName' is defined but never used.

JSHINT isn't much good if you don't pay attention to what it's telling you.


Also, your inner loop looks odd.

for (var j = i; i + nyName.length; i ++) {

Seems like it'll cause an infinite loop. You're perhaps wanting j with a different condition.

Upvotes: 1

matt b
matt b

Reputation: 139921

A typo in the for loop that wants to refer to myName would appear to be a big problem:

for (var j = i; i + nyName.length; i ++)
                    ^

Upvotes: 0

Mike Corcoran
Mike Corcoran

Reputation: 14565

You misspelled myName in your for loop syntax and typed nyName instead, so chances are the script dies as soon as it hits that line.

Upvotes: 0

Related Questions