Reputation: 117
I'm doing a code academy tutorial that searches text for my name and then pushes it into an array and console.logs it. I'm having an issue, the position of the letters is being logged to the console instead of the actual letters themselves. here is my code:
/*jshint multistr:true */
var text = "blah bleh blih bloh blah blah mike bleh tak tik mike";
var myName = "mike";
var hits = [];
for (i = 0; i < text.length; i++){
if (text[i] ==="m"){
for (j = i; j <= i + myName.length; j++){
hits.push(j);
}
}
}
if (hits.length === 0){
console.log("Your name wasn't found!");
} else {
console.log(hits);
}
the preceding code displays [ 30, 31, 32, 33, 34, 48, 49, 50, 51, 52 ] which is the position of the letters in my text variable, instead of the letters themselves
Upvotes: 0
Views: 135
Reputation: 39532
It's smarter to use Regular Expressions for this sort of thing. To find instances of a substring in a string:
var str = 'Greetings, SomeKittens, how are you, SomeKittens?';
var nameCount = str.match(/SomeKittens/g).length;
Upvotes: 1
Reputation: 166066
So, you know the position of the letters is in the variable j
, before it's pushed on to hits
.
You know those position refer specifically to the variable text
.
You already refereed to a letter at a specific position in text
with text[i]
.
So what could you push onto hits instead of j
to refer to the specific letter at j
's position in text
?
(if you just want to answer comment below — I'm never sure with code academy questions)
Upvotes: 2