Search code examples
javascripthtmltextareainnerhtmlhta

Replace text with linebreaks in a string that goes to a textarea


I'm making a HTA-App for formating a long list of numbers to match the filter from Microsoft Dynamics AX.

The script gets the list from the clipboard and format it to paragraphs á 26 numbers and finaly print it to a textarea.

My problem: i don't know how to replace text with linebreaks for the paragraphs.

i tried str.replace("text", "\r") as well as str.replace("text", "\n") but it wont work.

It's maybe a bit complicated, but it works good and fast, exept the paragraphs..

here is the script:

function start() {
  document.getElementById("dynamic").innerHTML = '<textarea id="to"></textarea>';
  document.getElementById("backbutton").innerHTML = '<img onClick="reset()" id="Back" src="src/back.png" alt="Zurück">';

  var cnt = 0;
  document.getElementById("to").innerHTML = window.clipboardData.getData('Text');
  var to = document.getElementById("to").value;

  var num = to.search(" ");
  if (num > 0) {
    for (num = 1; num > 0; cnt++) {
      var num = to.search(" ");
      if (cnt > 26) {
        var to = to.replace(" ", "ABSATZ");
        var cnt = 0;
      } else {
        var to = to.replace(" ", "\,LEER");
      }
    }

    for (nex = 1; nex > 0;) {
      var nex = to.search("LEER");
      var to = to.replace("LEER", " ");
    }

    for (nex2 = 1; nex2 > 0;) {
      var nex2 = to.search("ABSATZ");
      var to = to.replace("ABSATZ", "PARAGRAPHS HERE");
    }
  }
  document.getElementById("to").innerHTML = to;
}

Solution

  • replace with a string will only replace the first match. To replace all matches, you need to use a regular expression with the g flag:

    str = str.replace(/text/g, "\n");
    

    Be sure to escape any characters that are special in regular expressions.


    You only need to declare a variable once. Putting var before every variable assignment in your code is both unnecessary and confusing.