How did you fine-tune the "search text for your name program"?


#1

At the end of the search text for your name exercise, you get the following qustion:

"Think about how you might fine-tune this program to make sure it only finds exact matches for your name. Search the Internet to see if there are any built-in JavaScript string methods that can help!"

My question to you is, how did you work this out?

This is how i did it:

var text = "Let's hope this function of Geert works, it took a while before Geert understood this".split(" ")
var myName = prompt("what are you looking for?")
var hits = []

for (var i=0; i<text.length; i++){
if(text[i]===myName){
    hits.push(text[i]);
    }
};
if(hits.length===0){
    console.log("your search wasn't found")}
    else{
        console.log(hits) }

I'm looking forward to your solutions!


#2

"Search the Internet to see if there are any built-in JavaScript string methods that can help!"

Simply following the instructions or searching the internet may be a better solution than asking, sometimes.


#3

The entire program can be replaced with

var x = text.match(/Geert/g);
console.log(x);


#4

I tuned it to catch full word and then to check if it is actually your name. If so, then it pushes whole name into hits array. It also tells you the number of hits of yout name in the text.

var text = "your Text here"
var myName = "yourName"
var hits = []

for (var i=0; i < text.length; i++) 
{
    if (myName[0] === text[i])
    {
        var isItName = [];
        var theResult = "";
        
        for (var j = i; myName.length + i > j ; j++)
        {
            isItName.push(text[j]);
        }
        
        for (var s = 0; s < isItName.length; s++)
        {
            theResult = theResult + isItName[s];
        }
        
        if (theResult === myName)
        {
        hits.push(theResult);
        }
    }
}
if (hits[0]==="")
{
    console.log("Your name wasn't found!");
}
else
{
    console.log(hits);
    console.log("Your name appeared in the text " + hits.length + " times.");
}

#5

It is working well !

could you please provide further information for steps especially for why you defined isItName or theResult.


#6

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