This method checks for the first appearance of a provided string argument within the calling string and returns the index. It returns
-1 if the string argument can’t be found within the calling String.
""Hello and welcome to the scotch.io glossary, the end"".indexOf(""the"") // 21
// New String let sentence = "find the index of the first occurrence of me in this sentence" const keyWord = "me" let keyWordIndex = sentence.indexOf(keyWord) console.log(keyWordIndex) // 42
- Takes a string argument
- Checks if the provided argument exists within the calling string object
- Returns the index of the first appearance of the provided argument,
-1if it can’t be found.
const indexOfWord = string.indexOf(searchParam, startIndex)
This is the parameter to search for within the string -
This is the index at which the search will begin. Search typically begins from the
arr.length - 1 index, which is the last position in the string. If the value provided is less that
0, the string will not be searched.
This method returns a number which is the index of the first occurence of the searched string.
The indexOf() method is case sensitive
.indexOf() method is commonly used to verify the first occurence and position of a word in a sentence.
// New sentence const sentence = 'Friday is the last day'; // Keyword to be searched for const day = 'Friday'; // Find index of keyword const hasDay = sentence.indexOf(day); // log output console.log(hasDay); // 0
Want to improve your coding and design skills?
I'm continually researching the best practices and tools for coding.
Join 50,000+ developers looking to make cool stuff.
We value your privacy. 1-click unsubscribe.
Chris Sev is the co-founder of Better Dev. Coding better every day. Previously he created Scotch.io which was acquired.
What did you think of the article? Let us know!
(these comments are powered by GitHub issues and use 0 trackers)