Animations
API
Arrays
Async
Basics
Challenges
Classes
Console
Dates
Debugging
DOM Elements
DOM Methods
DOM Properties
Event Listeners
Flow Control
Forms
Functions
Global Functions
JSON
Keywords
Libraries (3rd party)
Math
Modules
Objects
Snippets
String
Types
Widgets
Window Object
The indexOf()
method returns the index of (the position of) the first occurrence of a specified text in a string. If it
is NOT found, it will return a -1. 0 is actually the very first position (zero based) so it's possible o is return as a
positive test.
let str = "Please locate where 'Hello World' occurs!";
let pos = str.indexOf("Hello World")
document.getElementById("demo1").innerHTML = "The position of Hello World is: " + pos + ".";
let str2 = "Please locate where 'Hello World' occurs!";
let pos2 = str.indexOf("Ricky Bobby");
document.getElementById("demo2").innerHTML = "The position of Ricky Bobby is: " + pos2 + ".";
The indexOf()
also works with arrays! You can use it to determine if something is found within an array. If it is NOT
found, it will return a -1. 0 is actually the very first position (zero based) so it's possible o is return as a
positive test.
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var a = fruits.indexOf("Apple");
The result of a will be 2 meaning that "Apple" is located at position 2 in the array.