Trying to improve "search text for your name" script



I am a complete novice to coding all together and just about getting to grips with the basics of Javascript, thanks to Codecademy :slight_smile:.

Below I have tried to improve on the search text for your name script to not just return anything that starts with a 'K' and to to return only my exact name and it works, for the most part. My problem is that it also returns loads of lines of Your name was not found! and loads of lines of my name, my question is why is it doing this and how can I improve the code to stop it?

Thanks very much,

/*jshint multistr:true */
var text = "ijbwdn iec enejnd \ aeiofniaowe raelfo Kieran \ raeivnisnaeon weiunv kierab twejnfd Kieran"
var myName = "Kieran";
var hits = [];
for(var i = 0; i < text.length; i++){
    if(text[i] === 'K'&&text[i+1] === 'i'&&text[i+2] === 'e'&&text[i+3] === 'r'&&text[i+4] === 'a'&&text[i+5] === 'n') {
        for(var j = i; j<= i+5; j++){
if (hits.length===0){
    console.log("Your name wasn't found!");


If you put something in a loop you should expect it to repeat.


When running the original version of the script from the lesson it just returns the name the amount of times that it appears in the text, with my modified version it gives loads of my name and loads of "Your name wasn't found!".

I'm not sure what I've done wrong to make this happen.


If you want it to happen only once, put it outside the loop, after the search is done.


Ah, I see what I've done.



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