print JS object in a div with new line instead of \n

Viewed 851

I am printing some JS object in a div. JS object is having a key with value being a string with newline.

String

one
two
three

Expected value in div:

one
two
three

What I am getting in div

one\ntwo\nthree

Code:

const textarea = document.querySelector("#textarea");
const log = document.querySelector("#log");

textarea.addEventListener('keypress', (event)=>{
 log.innerHTML = JSON.stringify({name:event.target.value});
});
<div id="log"></div>
<textarea name="" id="textarea" cols="30" rows="10"></textarea>

enter image description here

4 Answers

Newline characters are not permitted in JSON; JSON.stringify will never result in a string with a literal newline character. Stringifying something with a newline character will result in the output string containing a literal backslash character, followed by a literal n character, which is what you're seeing here.

If you actually need JSON.stringify, replace all \ns in it with actual newline characters.

Another problem is that newline characters do not normally result in actual newlines in the rendered HTML, for most elements. You might use a <pre> instead of a <div>, since <pre>s do render newlines in their contents as actual newlines:

const textarea = document.querySelector("#textarea");
const log = document.querySelector("#log");

textarea.addEventListener('keypress', (event) => {
  log.textContent = JSON.stringify({
    name: event.target.value
  })
    .replace(/\\n/g, '\n');
});
<pre id="log"></pre>
<br>
<textarea name="" id="textarea" cols="30" rows="10"></textarea>

(keep in mind that the contents of the #log element will not be valid JSON - you won't be able to copy its contents and JSON.parse it)

Use escape character \

{"name":"one\\ntwo\\nthree"}
  1. You have to replace \n with <br>
  2. Should use keyup instead of keypress otherwise you could only get the current value in the textarea

const textarea = document.querySelector("#textarea");
const log = document.querySelector("#log");

textarea.addEventListener('keyup', (event)=>{
 log.innerHTML = event.target.value.replace(/\n/g, '<br>')
});
<div id="log"></div>
<textarea name="" id="textarea" cols="30" rows="10"></textarea>

just replace keypress by keyup

const log = document.querySelector("#log");
const textarea = document.querySelector("#textarea");


textarea.addEventListener('keyup', (event)=>{
 log.innerHTML = JSON.stringify({name:  event.target.value.replace(/\n/g, '<br>')})

});
<div id="log"></div>
<br>
<textarea name="" id="textarea" cols="30" rows="10"></textarea>

Related