PLATFORM
  • Tails

    Create websites with TailwindCSS

  • Wave

    Start building the next great SAAS

  • Pines

    Alpine & Tailwind UI Library

  • Auth

    Plug'n Play Authentication for Laravel

  • Designer comingsoon

    Create website designs with AI

  • DevBlog comingsoon

    Blog platform for developers

  • Static

    Build a simple static website

  • SaaS Adventure

    21-day program to build a SAAS

Written By

What is indexOf() in JavaScript?

What is indexOf() in JavaScript?

After a long time, a new post on JavaScript methods is here... Let's learn about the indexOf() method.


indexOf()

It accepts two parameters: The required parameter of searchValue indicates the content you want to search for in a string.

The optional start parameter indicates the position of the string in which the search will begin. If not specified, the search will start at the beginning. indexOf is case sensitive but can be sued with regex case-insensitive modifier.

**TLDR: Returns the position of starting point of work or -1 if not found.


const movieQuote = "I'm in a glass case of emotion!"

console.log(movieQuote.indexOf("emotion", 20)); 

//output
23

console.log(movieQuote[23]); 
//output
e

Use Case

indexOf can creatively be used for many things, including validation. This is used for dynamic content by finding a word and displaying that content as output or in the example below, push the item into a new array if not already existent.

const updateVegetablesCollection = (veggies, veggie) => {
    if (veggies.indexOf(veggie) === -1) {
        veggies.push(veggie); 
        console.log(`New veggies collection is: ${veggies}`); 
    } else if (veggies.indexOf(veggie) > -1) {
        console.log(`${veggie} already exists in the veggies collection.`); 
    }
}

let veggies = ['potato', 'tomato', 'chillies', 'green-pepper']; 

updateVegetablesCollection(veggies, 'spinach'); 
//output
New veggies collection is : potato,tomato,chillies,green-pepper,spinach

updateVegetablesCollection(veggies, 'spinach'); 
//output
spinach already exists in the veggies collection.

🤩Thanks For Reading | Happy LearningšŸ„‚

Comments (0)

loading comments