Crkva Kovacica Crkva Kovacica - 4 months ago 9
Javascript Question

How to fix this program so it searches only my name?

I am learning JavaScript and i built this program, that searches for instances of the letter E within the

String
, and than stores letter by letter to an
array
but now when it finds a similar instance of the letter E it also outputs the similar instance, in this case i have Eddie, and Eric. And i don't want it to output the similar instance which is Eric in this case. I know there is a hacky way to do it, something like
if(nameYouFound !== "myName")
. But i don't like it... On the website where i learned this, it says there is built in JavaScript,
string
method that can help. Do you know what is the method that can solve the problem?


Please don't answer with JQuery, i am trying to get better at
JavaScript...



Here is the code snippet:



/*jshint multistr:true */
var text, myName, hits, i, j;
text = "Hello, there, how are you feeling Eddie hope you are ok, ok Eric";
myName = "Eddie";
hits = [];
for (i = 0; i < text.length; i++) {
if (text[i] === "E") {
for (j = i; j < (myName.length + i); j++) {
hits.push(text[j]);
}
}
}

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




Answer

You can use the built-in indexOf() method for strings.

var text = "Hello, there, how are you feeling Eddie hope you are ok, ok Eric";
var myName = "Eddie";
var hits = [];
var startIndex = text.indexOf(myName);
if (startIndex !== -1) { // myName exists in text
    for (var i = startIndex; i < startIndex + myName.length; ++i) {
        hits.push(text[i]);
    }
}
else {
    // Do whatever you want like.. 
    console.log("Not Found!")
}