Dust_In_The_Wind
Dust_In_The_Wind

Reputation: 3692

JS code to search exact occurrence of name in a text of characters

While going through the javascript basics on an online tutorial, I came across a problem, which searches for the occurrence of a person's name in a given set of characters (a string). The solution as discussed in the tutorial just copies n set of characters from the original string, beginning with a matching first letter, to an empty array. Here, n is the length of a person's name from the name array.

To modify the code such that the program copies only exact occurrences of a person's name into the empty array, I wrote this solution, but it has one flaw:

 var text = "Hey, how are you \
doing? My name is Manish. It's a really hot day in here. Nice to meet you \
Manish. Bye";
var myName = "Manish";

var hits = [];

for(var i = 0; i < text.length; i++) {
    if(text[i] === myName[0]) {

        for(var j = i, k = 0; j < myName.length+i, k < myName.length; j++,k++) {
                //if first letter is a match, check if next letter is a match
                if(!(text[j+1] === myName[k+1])) {
                    break;
                }
                else {

                    hits.push(text[j]);
                }
        }
    }

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

The last letter of the name is never printed (or pushed to the hits array). The output I get is:

["M", "a", "n", "i", "s", "M", "a", "n", "i", "s"] 

What am I doing wrong?

Upvotes: 0

Views: 153

Answers (3)

baao
baao

Reputation: 73251

It would be easier with indexOf();

var name = 'Manish';
var str = 'Hey, how are you \\ndoing? My name is Manish. It\'s a really hot day in here. Nice to meet you \\nManish. Bye';
if (str.indexOf(name)>-1) {
 alert('Name was found');
} else {
 alert('Your name wasn\'t found');
}

Upvotes: 0

gilly3
gilly3

Reputation: 91587

You are adding 1 to your counter variables when you make the comparison:

if(!(text[j+1] === myName[k+1]))

but then you are adding the character without adding 1 to the counter variables:

hits.push(text[j]);

Just don't add 1 to your counter variables:

if(!(text[j] === myName[k]))

There are other comments I could make about your code, but since you are learning, I hesitate to say too much. I should say this, at least: Look what happens to your output, when you change text to this:

var text = "Hey, how are you doing? My name is Manish. My, it's a really hot day in here. \
Maybe I'll go outside. Nice to meet you Manish. Bye";

Upvotes: 0

Amit
Amit

Reputation: 46351

Because your inner loop compares the "next" character, and if that matches pushes the current character. By the time you're "ready" to push the last matching character, you're comparing the next one, and that's not matching. myName[k+1] will actually be undefined.

Try like this: if(!(text[j] === myName[k])) {

Upvotes: 2

Related Questions