Posts

Showing posts with the label indexOf

๐Ÿง  How to Use indexOf() in JavaScript – Complete Guide with Examples

Image
๐Ÿ” 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); ...