Javascript String Search with indexOf() and lastIndexOf()

Description

Javascript String Search with indexOf() and lastIndexOf()

View in separate window

<html>
   <head>
      <title>
         Searching Strings with indexOf and lastIndexOf
      </title>
      <script type = "text/javascript">
         let letters = "abcdefghijklmnopqrstuvwxyzabcdefghijklm";
         // w  w  w.jav a  2s  . c  om
         function buttonPressed() 
         {
            let searchForm = document.getElementById( "searchForm" );
            let inputVal = document.getElementById( "inputVal" );

            searchForm.elements[2].value = 
               letters.indexOf( inputVal.value );        
            searchForm.elements[3].value = 
               letters.lastIndexOf( inputVal.value );    
            searchForm.elements[4].value = 
               letters.indexOf( inputVal.value, 12 );    
            searchForm.elements[5].value = 
               letters.lastIndexOf( inputVal.value, 12 );
         }
      </script>
   </head>
   <body>
      <form id = "searchForm" action = "">
         <h1>The string to search is:<br />
             abcdefghijklmnopqrstuvwxyzabcdefghijklm</h1>
         <p>Enter substring to search for 
         <input id = "inputVal" type = "text" />
         <input name = "search" type = "button" value = "Search"
                onclick = "buttonPressed()" /><br /></p>
      
         <p>First occurrence located at index 
         <input id = "first" type = "text" size = "5" />
         <br />Last occurrence located at index
         <input id = "last" type = "text" size = "5" />
         <br />First occurrence from index 12 located at index 
         <input id = "first12" type = "text" size = "5" />
         <br />Last occurrence from index 12 located at index
         <input id = "last12" type = "text" size = "5" /></p>
      </form>
   </body>
</html>



PreviousNext

Related