Trying to improve "search text for your name" script


#1


https://www.codecademy.com/courses/javascript-beginner-en-XEDZA/0/7?curriculum_id=506324b3a7dffd00020bf661


Hi,

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,
Kieran


/*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++){
            hits.push(text[j])
        }
    }
if (hits.length===0){
    console.log("Your name wasn't found!");
}else{
    console.log(hits);
}
}


#2

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


#3

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.


#4

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


#5

Ah, I see what I've done.

Thanks.


#6

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