online software programming courses

JavaScript indexOf function

In this tutorial, you learn how to use Javascript indexOf function with examples.

Must know about IndexOf() method

1. Using this you can find substring position inside a string or inside an array

2. This function returns -1 if the substring position not found inside string

3. Returns the index position if the substring is found at first occurence.

4. It's a case sensitive function. It means small and capital letters are treated differently. 

<!DOCTYPE html>
<html>
<head>
    <title>
        JavaScript indexOf Method
    </title>
</head>
  
<body>
    <script>
        let str ="I am a blogger"
        let subString="a"

        let index=str.indexOf(subString)
        console.log(index);
    </script>
</body>
  
</html>

The above script returns 2 as the index position.

It's a case-sensitive function, which means uppercase letters and lowercase letters are treated differently. 

Let's see another example

<!DOCTYPE html>
<html>
<head>
    <title>
        JavaScript indexOf Method
    </title>
</head>
  
<body>  
    <script>
        let str ="JavaScript a cool language"
        let subString="java"

        let index=str.indexOf(subString)
        console.log(index);
    </script>
</body>
  
</html>

The console log will output -1 since, it can not find the sub-string "java" in it. The main string has "Java" not "java", which proves it a case-sensitive function

Let's see another example. In this example we use an array of objects.

<!DOCTYPE html>
<html>
<head>
    <title>
        JavaScript indexOf Method
    </title>
</head>
  
<body>
    <script>
      let fruits = ["Banana", "Orange", "Apple", "Mango"];
      let index = fruits.indexOf("Apple");
      console.log(index);
    </script>
</body>
  
</html>

The above JavaScript code would print 2 on the console. 

So indexOf returns an index position from a string or an array objects. If it can not find it returns -1.