Programming, Music, Games. Creation.

Search exact text – Java Script

findstring

/*Coded my Bermuda
imnotbermuda.com*/

var text = "LOL LOL MAX LOL LOL LOL MIX LOL\
 MII LOL MIN MAX LOL LOL LOL LOL LOL \
 MAA LOL LOL \
 MIT LOL MAX MAT LOL LOL LOL";
var myName = "MAX";
var hits = [];

for(i=0; i<text.length; i++){
 var counter = 0;//reset counter

//event triggers ONLY if the first letter of myName was found
 if(myName[0] === text[i]){
 /*
 The following code does this :
 check whether myName's [j-i]th letter matches with text's [j]th letter (that means the first check will be myName[0] since in the first loop, j=i. As the loop progresses, difference between j and i will increase.
 If they match, counter increases.
 loop this for the length of myName to check for every letters in myName.
 */
 for(j=i; j<(i+myName.length); j++){
 if(myName[j-i] === text[j]){
 counter++;
 }
 }
 }

 if(counter==myName.length){
 /*
 if the counter above equals to the length of myName,
 it means myName[0]=text[j], myName[1]=text[j+1]... was accomplished, proving the exact string was found.
 therefore, push the entire name to hits variable.
 */
 hits.push(myName)
 }
}

if(hits.length===0){
 console.log("Couldn't find shit");
} else {
 console.log(hits)
 console.log(myName + " was found " + hits.length + " times")
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s