What is JavaScript indexOf()?
👨🏻‍💻

What is JavaScript indexOf()?

Created
Apr 26, 2021 08:43 AM
Tags
5 Mins read
JavaScript
Web Dev
Programming
Description
A brief explanation of what is the javascript method indexOf()?
Updated
Last updated April 28, 2021

So what is indexOf()?

indexOf() finds the first occurrence of a string and returns the index. So an example:
let example = 'Hello World'; console.log(example.indexOf('e')); // 1
The above should return 1. Because the letter 'e' in the string is at index 1.
 
But if the indexOf() string does not exist like example:
let example = 'Hello World'; console.log(example.indexOf('t')); // -1
It will return -1 if it does not exist.
 
It will always return the first occurrence even if the indexOf() string is not a letter but a word.
let example = 'Hello World'; console.log(example.indexOf('ello'); // 1

More in this series: