Suggestion


#1


Hello,
I have made a little edit in the code to make it search for any letter -that managed to me use only 1 for loop instead of 2 - in the text and prints out the letter and 7 successive characters. It works perfectly but still needs some improvements_ :slight_smile:

I will be grateful for any suggestions and collaborations.


var text = 'Hacker is a person who enjoys exploring the details of \  programmable systems and how to stretch their capabilities, as opposed \ to most users, who prefer to -Programmer Pom-  learn only the minimum necessary';
var myName = prompt("Enter your name's first letter!");
var hits = [];
for (i=0; i < text.length; i++){
    if(text[i] === myName[0]){
        var loc = i;     // a variable to get the 'location' of the letter entered.
        hits.push(text.substring(loc, loc+7));
    }
}
if(hits.length === 0){
    console.log("Your name was not found");
}else{
    console.log(hits);
}


#2

why +7? this assumes you know the length of of the name, it would be better not to hard code this:

hits.push(text.substring(i, i+myName.length));

and you can just use i, since i contains the right index thanks to the if statement


#3

But I have substituted the name with a prompt that asks the user to enter a letter to search for.

Edit: You are right. But I intend to make the user enter a letter to search it.


#4

okay, but it wouldn't be nicer to ask the user to enter a text, and the name to search for?

few suggestions/tips:

string comparison is case sensitive, so if the user enters i, the i in is and details are also included. Maybe a idea to convert the result of prompt to an uppercase?
there is no validation of user input (lesson 1 in prompting the user for input: don't trust them, always validate), what if the user enters more then 1 letter?

it really depends what the purpose of your program is


#5

Thanks, I will improve the code using these tips.


#6

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