Question

So, I am brand spanking new to JavaScript. I am practicing right now with a Codeacedemy tutorial, and it had me create a program that finds my name in a string of text. But, I realized that if I use a name thats similiar to mine, it will return the other name too. What method can I use or how can I refine the code so that it will only match the exact name in the string?

Here's the code:

/*jshint multistr:true */

var text = "Hello my name is Zachary Sohovich. I'm a 20 year old dude from Southern California and I love to code";
var myName = "Zachary";
var hits = [];
for (var i = 0; i < text.length; i++){
    if (text[i] == 'Z') {
        for (var j = i;j < (i + myName.length); j++) {
            hits.push(text[j]);
        }
    }
}
if (hits === 0) {
    console.log("Your name was not found!");
}
else {
    console.log(hits);
}
Was it helpful?

Solution

You could String.split the string at the white spaces to create an array of words and then check each word against your test string, thus preventing matches within a substring. (with an alternative loop while)

Javascript

var text = "Hello my name is Zachary Sohovich. I'm a 20 year old dude from Southern California and I love to code",
    myName = "Zachary",
    hits = 0,
    array = text.split(/\s/),
    length = array.length,
    i = 0;

while (i < length) {
    if (myName === array[i]) {
        hits += 1;
    }

    i += 1;
}

if (hits === 0) {
    console.log("Your name was not found!");
} else {
    console.log(hits);
}

On jsfiddle

Or if you really want to have fun with checking the string by loops then you could do something like this.

Javascript

var text = "Zachary Hello my name is Zachary Sohovich. I'm a 20 year old dude from ZacharySouthern California and I loZacharyve to code Zachary",
    textLength = text.length,
    myName = "Zachary",
    nameLength = myName.length,
    check = true,
    hits = 0,
    i = 0,
    j;

while (i < textLength) {
    if (check) {
        if (i !== 0) {
            i += 1;
        }

        j = 0;
        while (j < nameLength) {
            if (text.charAt(i + j) !== myName.charAt(j)) {
                break;
            }

            j += 1;
        }

        if (j === nameLength && (/\s/.test(text.charAt(i + j)) || i + j === textLength)) { 
            hits += 1;
            i += j;
        }
    }

    i += 1;
    check = /\s/.test(text.charAt(i));
}

if (hits === 0) {
    console.log("Your name was not found!");
} else {
    console.log(hits);
}

On jsfiddle

Note: there are a number of other possible solutions that will do the same for you.

OTHER TIPS

**

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

**

It'll do... easy one.

You need not do all those stuff.

Just find your name with following code

if(text.indexOf(myName) !== -1){
  console.log('Found');
}

If its the total number of occurrences you would like to find

var count = text.match(/Zachary/g).length; 
console.log(count)

Here's my enhanced version of that lesson.

/*jshint multistr:true */
var text = "Anastasius is known to have had a brother named Flavius Paulus, who served \
asRoman consul in 496. A sister-in-law, known as Magna, was mother to Irene and  \
mother-in-law to Olybrius. This Olybrius was son of Anicia Juliana and Areobindus \
Dagalaiphus Areobindus. The daughter of Olybrius and Irene was named Proba. She \
married Probus and was mother to a younger Juliana. This younger Juliana married another \
Anastasius and was mother of Areobindus, Placidia, and a younger Proba. Another nephew \
of Anastasius was Flavius Probus, Roman consul in 502. Caesaria, sister of Anastasius, \
married Secundinus. They were parents to Hypatius and Pompeius. Flavius Anastasius \
Paulus Probus Moschianus Probus Magnus, Roman Consul in 518 also was a great-nephew of \
Anastasius. His daughter Juliana later married Marcellus, a brother of Justin II. The \
extensive family may well have included viable candidates for the throne.";

var textAsWords = text.split(/\s/);

var myName = "Anastasius";

var hits = [];

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

if (hits === 0) {
    console.log("Your name was not found!");
} else {
    console.log(hits);
}

This is what I came up with, staying close to the original exercise.

This consisted of comparing each letter in the text to the first character of the name. On finding that character, you had to add it and any characters that followed into an array, only stopping when the number of characters were equal to the number of letters in the name.

Next, the student was asked to improve the code so it would only add letters matching the exact name. Because the original exercise did not use whitespace or searching for an occurence of the name in one complete string of letters, I did not either.

/*jshint multistr:true */
var text = "olleboleYntke Mchael MichaetMichael S1knol E E rin oef goblinMichael kdmS3ksMichael K  elkekeerifdlkùYnyslght MichaelSerind";
myName = "Michael";
var hits = [];
var getCharName = function(namePos) {
  charName = myName[namePos];
};

for (i = 0; i <= text.length; i++) {
  namePos = 0;
  getCharName(namePos);
  if (text[i] === charName) {
    var letterMatch = false;
    for (j = 0; j < myName.length; j++) {
      getCharName((namePos + j));
      if (text[(i + j)] === charName) {
        letterMatch = true;
      } else {
        letterMatch = false;
      }
    }
    if (letterMatch === true) {
      for (j = 0; j < myName.length; j++) {
        hits.push(text[(i + j)]);
      }
    }
  }
}
if (hits === 0) {
  console.log("Your name was not found!");
} else {
  console.log(hits);
}

I'm on the same exercise, and this is my answer.

The method first finds a match with the first letter of myName. When we find a match, we place a X marker on it and run down the text to see if there is a full match. If there is a full match, we return to the X marker and place the correct length of text into the output array "hits". After placing all the letters into the array, we return to the X marker to continue with the rest of the text.

If we don't have a full match, we return to our X spot and continue on to find a match with the first letter of myName again.

var text = "HahahnhahahahnhaHahahahahahahahahahahahaHahahahahahahahahahaHahahahahahnhaHahnhahahahahahahahahaHahaha"
var myName = "Hahn"

var hits =[] //the output will be an array

for(i=0; i<text.length; i++){ 
    var m = 0; 

    if(text[i] === myName[0]){ 
        for (j=0; j<myName.length; j++){ 
            if (text[i+j] !== myName[m]){ 
                break
            }
            m++; 
            if (m === myName.length){
                for (n=0; n<myName.length; n++){
                    hits.push(text[i+n]);
                }
            }
        }
    }
}

console.log(hits)

The shortest way of finding your name is to use .match example below:

var text = "Hello my name is Zachary Sohovich. I'm a 20 year old dude from 
Southern California and I love to code";

var nameCheck = text.match(/zachary/gi)
console.log(nameCheck)

Note that THE gi after your name this tells the console to log all matches irrespective of case to use. You can also use .match to also be case sensitive by replacing gi with g.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top