Why doesn't this work to find my name even if its written twice?


In the last section it said to try to find a way to make it so it will find an exact match. Why doesn't this work?

var text = "bla bla bla olin olin bla";
var myName = "olin";
var hits = [];

for (ti = 0; ti < text.length; ti++) {
    if (text[ti] === text.indexOf("olin")) {
        for (ni = ti; ni < (text.indexOf("olin")) + (myName.length); ni++) {



The above is a character, only.

The above is an integer.


will always find the same index. Look up lastIndexOf() to work around this problem.



Thanks. I missed the fact that it was an integer and not a character. I made it work by changing
(text[ti] === text.indexOf("olin")) to (text[ti] === text[text.indexOf("olin")])


Go to this page, and F3 the link text, Method 1. substring

Keep scrolling until you reach the segment on indexOf, and further down there is lastIndexOf. That whole topic was practice code, so there isn't a message pertaining to this topic. Just thought you might find it interesting.

Also, although not the same topic, it touches on lastIndexOf, this too you could find interesting.


Thanks for sharing! I will definitely check it out.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.