Daniel Williams Daniel Williams - 26 days ago 11
Javascript Question

Preserve line breaks from javascript string on paste into textarea

Seen similar questions on SE without an answer.

If I click the button in the code, I alert the string and it's formatted with line breaks in the alert. When the string is then pasted into the textarea, all line breaks are removed.



function pasteText() {

var theText = "a\nb\nc";
alert(theText);
document.getElementById("theText").innerText = theText;
}

<textarea id="theText"></textarea>
<br><button onclick="pasteText()">Click</button>





NOTE: This is only an issue in Firefox

Answer
  1. Use textContent instead of innerText

See snippet below

function pasteText() {
    
  var theText = "a\nb\nc";
  alert(theText);
  document.getElementById("theText").textContent = theText;
}
<textarea id="theText"></textarea>
<br><button onclick="pasteText()">Click</button>

  1. or innerHTML

function pasteText() {
    
  var theText = "a\nb\nc";
  alert(theText);
  document.getElementById("theText").innerHTML = theText;
}
<textarea id="theText"></textarea>
<br><button onclick="pasteText()">Click</button>

Comments