Victory Lesson: Perfecting Code


#1

I tried to use the .match method to search the text string for "myName" rather than specifying ("Pawel"/g), however I am getting a reference error.

I realize it would be easier to simply use ("Pawel"/g), however lets say you prompt a user for the name, how can you search against it in a string?

Is there anyway around this?


var text = ("Hey how are you, my \
    name is Pawel! Did I mention my name Pawel?");
var myName = ("Pawel");
var hits = [];

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

var nameSearch = text.match(myName/g);

if (namesSearch.length === null) {
    console.log("Your name wasn't found!"); }
else {
    console.log("Your name was found" + nameSearch.length + " times!"); 
}


#2
  1. text.match(myName/g)//wrong //add /
    text.match(/myName/g)//right
    2.if (namesSearch //wrong //remove "s"
    if (nameSearch//right
    you have more mistake

@agentpawel


#3

I've made the recommended changes but am still getting an error:

TypeError: null is not an object (evaluating 'nameSearch.length')

I suspect by adding the forward slash in .match parenthesis, does it not simply search for that text rather than the variable?


#4

Actually text.match(/myName/g) means
you are ordering to search "myName" inside text variable

any question?

@agentpawel


#5

I'm trying to order it to search the variable myName, which is the above.


#6

yes i know
then you should write
myName.match(/Pawel/g)
means search "Pawel" inside MyName varible.

i'm not telling you the answer. it'll make sense :slight_smile:

@agentpawel