Complete BLoC with Clean Architecture (group chat) Discount !! E-commerce App With Backend Source Code Video and Voice Chatting App Firebase Chatting App Source Code Complete Gym App BLoC State Management Source Code Complete Study App Buy Ticket Booking App Source Code Buy Travel App With Backend Source Code Complete Chat App Udemy Course Special Offer Discount !! Online Learning Course App (BLoC) Online Learning Course App (Riverpod) Online Learning Course App (Getx) Discount !! Shopping App (Provider) Cool Flutter Game Flutter Nodejs Chat App Flutter Nodejs Api And Firebase Chat App Riverpod Task Management App
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.