7/7 Victory!


#1

Hey guys has any of you found the JavaScript methods which we can use to make sure the program just print out our name. Okey, what I wanna to say is this:

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!

This is my code:

var text = "Blabla blabla bla bla bla Jonathan bla bla bla / blabla Jonathan blabla bla";

var myName = "Jonathan";

var hits = [];

for (var i=0; i < text.length; i++) {
if (text[i] ==="J"){
for (var j=i; j< (myName.length + i); j++){
hits.push(text[j]);
}
}
}

if(hits.length === 0){
console.log("Your name wasn't found!");
}else{
console.log(hits);
}

which works pretty well, but whatabout if I type this:

Blabla blabla bla bla bla Jonathan bla bla bla / blabla Jhosua blabla bla

Both names start with "J" , but my var myName = "Jonathan"; so how can I be sure the program does not log the name Jhosua in the console.

Thanks


#2

I also had such an idea. Actually you don't need anything new. That's how I did it:

/*jshint multistr:true */

var text = "Mac Msx Maz Mqc Nax Ma Max Mwx Jax Mx Amx Max Mxx";
var myName = "Max";
var hits = "";
var foundData = "";

for (var i = 0; i < text.length; i++) {
    for (var j = 0; j < myName.length; j++) {
        if (text[j+i] === myName[j]) {
            foundData += myName[j];
        }
    }
    if (foundData === myName) {
        hits = hits + myName + " ";
    }
    foundData = "";
}

if (hits.length === 0) {
    console.log("Your name wasn't found!");
} else {
    console.log(hits.substring(0, hits.length - 1));
}

In my code "hits" isn't an array, but it can be, as well.


#3

Thanks a lot @maxtirdatov


#4

seems like working but I just can't seem to understand the script... :confounded:


#5

I with you on this one, it works but i don't udnerstand it and thats the point of us taking this course, is to learn it and be able to write it.


#6

The code is not perfect! If the name is "Maxx", it can be found as "Max".


#7

I do this using the substring code. text.substring(x,y) calls the elements of text located in positions x through y. This can be used to look for instances of the full name.

/*jshint multistr:true */

var text = "A bunch of text which contains my name, which is Bert.  Bert is my name.  My full name is Bernard Humperdink";

var myName = "Bert";

var hits = [];


for(i=0; i<=text.length; i++){
    if(text.substring(i,i+myName.length) === myName){
        // Technically this also needs an if statement to check that the code is detecting the name and not a word containing the name e.g. by checking that text[i-1] and text[i+myName+1] are spaces, punctuation or outside the domain of the array.
        for(j=i; j<i+myName.length; j++){
            hits.push(text[j]);
        }
    }
}

if(hits.length == 0){
    console.log("Your name wasn't found");
}
else {
    console.log(hits);
}