Reputation: 3
I am currently trying to get my .indexOf to read the position of my characters in my string.
Here is what the code looks like:
var myString = 'I\'m a "fun ninja" string';
if (myString.indexOf("ninja") === -1)
{
console.log ("The word ninja starts at position " + myString.indexOf("ninja"));
} else {
console.log ("The word ninja is not in the string");
}
It's supposed to say, "The word ninja starts at position 11" but what it ends up saying is "The word ninja is not in the string", when it obviously is in the string. Can anyone tell me what I'm doing wrong?
Upvotes: 0
Views: 80
Reputation: 1705
This would give you the desired result. 2 things to note:
The string is built using single quotes, so any single quote inside that needs to be escaped with a backslash \
The comparison in the if
statement is wrong. You should check if the index is not -1, which means the string is actually there.
var myString = 'I\'m a "fun ninja" string';
if (myString.indexOf("ninja") !== -1) {
console.log ("The word ninja starts at position " + myString.indexOf("ninja"));
} else {
console.log ("The word ninja is not in the string");
}
Upvotes: 1
Reputation: 41
the problem is in your if statement, you are comparing if the result of indexOf is === -1, but if the indexOf function returns -1 it means that the substring isn't found, as he finds "ninja" in your string it doesnt execute the code and jumps to the else instead.
It should be:
if (myString.indexOf("ninja") != -1){
console.log ("The word ninja starts at position " + myString.indexOf("ninja"));
} else {
console.log ("The word ninja is not in the string");
}
Upvotes: 4