Improved version


#1


 /*jshint multistr:true */

var text, myName, hits;

text = "bla Leonard  bla Leonerd gda Leboba aga b a a Leonard \
Leoseld aah ahahra Leonard";

myName = "Leonard";

hits = [];

var counter = 0;

for(var i=0; i<text.length; i++) {
    if(text[i] === myName[0]) {
        hits.push(text[i]);
        for(j=1; j<myName.length; j++) {
            if(myName[j] === text[i+j]) {
                hits.push(myName[j]);
                console.log(hits); /* this line just helps to understand why
we need 'break'...it also works without the break but it's more effective
with it...(e.g.: when the algorithm checks "Leonerd"
it stops when it reaches the "e") */
            }
            else {
                break;   
            }
        }
        if(hits.length === myName.length) {
            counter++;
        }
        hits = [];
    }
}

if(counter === 0) {
    console.log("Your name wasn't found!");   
} else {
    console.log(counter);   
}


#2

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