'forEach not working if value is taken from input

I'm simply working on forEach, and I'm trying to get the values from the user input. If I directly give the value, the code is working but when I submit the value from input box, the code doesn't give expected results. I know that there is nothing to do with forEach in this case but can anyone say what should I do to fix this error.

In the first case, I'm submitting the towhat value, and this code is working well.

function hof() {
  var myString = document.getElementById("thetext").value;
  var sep = document.getElementById("sep").value;
  var limit = document.getElementById("limit").value;
  var towhat = document.getElementById("towhat").value;
  var fruits = myString.split(sep, limit);
  let text = "";
  fruits.forEach(myFunction);

  function myFunction(item, index) {
    text += index + ": " + item + "\n";
  }
  document.getElementById("demo").value = text;
}
textarea {
  width: 100%;
  height: 200px
}
<textarea id="thetext" readonly>Hello, this is just a sample text</textarea><br/><br/> 
separator : <input id="sep" value=" " readonly></input>
<br/><br/> 
For how many? <input id="limit" value="100" readonly></input><br/><br/> 
To what? <input id='towhat' value='index + ": " + item + "\n"' readonly></input><br/><br/>
<button id="" onclick="hof()">hooooof</button> <br/><br/>
<textarea id="demo"></textarea>

However, the second code doesn't work. But why? Both have the same values except a minor change, which is also almost the same as the first one. What should i do to fix this?

function hof() {
  var myString = document.getElementById("thetext").value;
  var sep = document.getElementById("sep").value;
  var limit = document.getElementById("limit").value;
  var towhat = document.getElementById("towhat").value;
  var fruits = myString.split(sep, limit);
  let text = "";
  fruits.forEach(myFunction);

  function myFunction(item, index) {
    text += towhat;
  }
  document.getElementById("demo").value = text;
}
textarea {
  width: 100%;
  height: 200px
}
<textarea id="thetext" readonly>Hello, this is just a sample text</textarea><br/><br/> 
separator : <input id="sep" value=" " readonly></input><br/><br/> 
For how many? <input id="limit" value="100" readonly></input><br/><br/> 
To what? <input id='towhat' value='index + ": " + item + "\n"' readonly></input><br/><br/>
<button id="" onclick="hof()">hooooof</button> <br/><br/>
<textarea id="demo"></textarea>


Solution 1:[1]

I think I found the problem.

// "towhat" is not a function, this is a string value.    
var towhat = document.getElementById("towhat").value;

// When you write it like this:
text += towhat;

// A code works like this:
text += 'index + ": " + item + "\n"'; 

You can get just index value by dynamic.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 yasgo