0

I am trying to embed text in a textbox after each line-break. Specifically, I want to add <div> at begining of each line in the textarea and ending up with </div>. I have tried this code but it just adds the text at the beginning and end of the value:

var arr = [document.getElementById("text1").value];
for( i=0; i<arr.length; i++ )
text2.value = '<div>' + arr[i] + '</div>';

It gives the output like:

<div>
text line 1
text line 2
text line 3
</div>

But all I want is this:

<div>text line 1</div>
<div>text line 2</div>
<div>text line 3</div>

OR

enter image description here Please help!

GreyRoofPigeon
  • 17,833
  • 4
  • 36
  • 59
  • `[document.getElementById("text1").value]` will give you only one result. You need to split the value on every line break, then you'll have multiple items in your array. – GreyRoofPigeon Sep 16 '22 at 07:41
  • As you can see is that your loop only goes through once and that can be explained by @LinkinTED 's comment – bylal Sep 16 '22 at 07:42
  • You have to [split](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split) `document.getElementById("text1").value` with the next line code as separator to get an array of the lines. – Geshode Sep 16 '22 at 07:44
  • Can please guide me on how to split value based on line break? As I've tried `split` and `splice` but failed. Came here after a lot of struggle. – Mohsin Ali Sep 16 '22 at 07:46
  • [Here](https://stackoverflow.com/a/21712066/9038475) is one way to split by new line. You can easily find those explanations, when searching for "split string by new line". – Geshode Sep 16 '22 at 07:53

2 Answers2

1

You should use "split" to split every newline, example:

const text1 = document.getElementById("text1");
const text2 = document.getElementById("text2");
const arr = text1.value.split("\n");
text2.value = "";
for( i=0; i<arr.length; i++ )
    text2.value += "<div>"+arr[i]+"</div>\n";
Supertommino
  • 562
  • 3
  • 13
0

Here a quick solution using plain Javascript:

  var valueFromTextbox1= document.getElementById('text1').value;
  valueFromTextbox1.split(/\r?\n|\r|\n/g).forEach(function(textline){
    let previousValue = document.getElementById('text2').value;
    document.getElementById('text2').value = previousValue + '<div>'+textline+'</div>'+"\n";
  });

mhaendler
  • 124
  • 5