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
CodePudding user response:
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";
CodePudding user response:
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";
});