๐ง How to Use indexOf() in JavaScript – Complete Guide with Examples
๐ What is indexOf() in JavaScript? The indexOf() method in JavaScript is used to find the position (index) of a specific element within a string or array . If the item is not found, it returns -1 . ๐งช Syntax For Strings: string.indexOf(searchValue, startIndex) For Arrays: array.indexOf(searchElement, fromIndex) ๐ How indexOf() Works in Strings const text = "JavaScript is amazing"; console.log(text.indexOf("Script")); // Output: 4 ✅ Case Sensitivity: console.log(text.indexOf("script")); // Output: -1 Note: indexOf() is case-sensitive. ๐ Finding the First Occurrence const sentence = "I love JavaScript because JavaScript is fun!"; console.log(sentence.indexOf("JavaScript")); // Output: 7 ๐ต️♂️ Find All Occurrences in a String const str = "JS is cool. JS is powerful. JS is everywhere!"; let index = str.indexOf("JS"); while (index !== -1) { console.log("Found at:", index); ...