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);
}
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.