Search code examples
javascriptcharat

Javascript- displaying words with charAt one letter+one letter and so on


So im trying to display words typed in my textbox as following example: (thomas) would display as= "t, th, tho, thom, thoma, thomas". What do i input in charAt to make that happen? or do i need to add something else? Thanks in advance!

<head>
  <meta charset="utf-8">

 <script>

    function printit()
    {
     var temptext = document.getElementById("mytext").value;   
     var tempa = temptext.charAt();
     document.getElementById("translated").innerHTML=tempa;

    }

 </script>


 </head>


 <body>
   <h1> </h1> 

<form name="f1">
 <input type="text" id="mytext" value="" />
 <input type="button"  value="print" onclick="printit()"/>

 </form>
 <div id="translated"  style="background-color:gray"></div> 

</body>


</html>

Solution

  • An ES6 solution using Array.from and String#slice methods.

    <script>
      function printit() {
        var temptext = document.getElementById("mytext").value;
        document.getElementById("translated").innerHTML = Array.from({
          length: temptext.length
        }, (v, i) => temptext.slice(0, i + 1)).join();
    
      }
    </script>
    
    
    <form name="f1">
      <input type="text" id="mytext" value="" />
      <input type="button" value="print" onclick="printit()" />
    
    </form>
    <div id="translated" style="background-color:gray"></div>


    Using Array#map and String#split methods.

    <script>
      function printit() {
        var temptext = document.getElementById("mytext").value;
        document.getElementById("translated").innerHTML = temptext.split('').map(function(v, i) {
          return temptext.slice(0, i + 1)
        }).join();
    
      }
    </script>
    
    
    <form name="f1">
      <input type="text" id="mytext" value="" />
      <input type="button" value="print" onclick="printit()" />
    
    </form>
    <div id="translated" style="background-color:gray"></div>