String indexOf()

indexOf() searches a string and return the position. indexOf() returns -1 if the substring isn't found.

indexOf() method does the search at the beginning.

 
<!DOCTYPE html>
<html>
<head>
    <title>Example</title>
    <script type="text/javascript">
    
        var stringValue = "hello world"; 
        document.writeln(stringValue.indexOf("o")); //4 

       
    </script>
</head>
<body>
</body>
</html>
  
Click to view the demo

An optional second argument tells where to start with.

 
<!DOCTYPE html>
<html>
<head>
    <title>Example</title>
    <script type="text/javascript">
    
        var stringValue = "hello world"; 
        document.writeln(stringValue.indexOf("o", 6)); //7 

       
    </script>
</head>
<body>
</body>
</html>
  
Click to view the demo
 
<!DOCTYPE html>
<html>
<head>
    <title>Example</title>
    <script type="text/javascript">
    
        var stringValue = "Lorem ipsum dolor sit amet, consectetur adipisicing elit"; 
        var positions = new Array(); 
        var pos = stringValue.indexOf("e"); 
        
        while(pos > -1){ 
            positions.push(pos); 
            pos = stringValue.indexOf("o", pos + 1); 
        } 
        
        document.writeln(positions); //3,13,15,29
       
    </script>
</head>
<body>
</body>
</html>
  
Click to view the demo
Home 
  JavaScript Book 
    Essential Types  

String:
  1. The String Type
  2. String length property
  3. String charAt()
  4. String charCodeAt()
  5. String concat()
  6. String slice()
  7. String substr()
  8. String substring()
  9. String indexOf()
  10. String lastIndexOf()
  11. String trim() Method
  12. String toLowerCase()
  13. String toLocaleLowerCase()
  14. String toUpperCase()
  15. String toLocaleUpperCase()
  16. String match()
  17. String search()
  18. String replace()
  19. String split()
  20. String localeCompare() Method
  21. String fromCharCode() Method
  22. String HTML Methods