0

After seeing this answer I was trying to find a way to update the contents of a <pre> tag and have the new-lines displayed using implicit new-lines (i.e. in the string literal). I tried setting various properties: innerHTML, innerText, textContent, nodeValue (after checking answers to this question) yet none seemed to have the white-space preserved.

I am aware I could use String.fromCharCode() - e.g. "Bob " + String.fromCharCode(10, 13) + "is "... but wanted to find a way using the former syntax as well.

//Perfectly valid code
var foo = "Bob \
is \
cool.";
document.addEventListener('DOMContentLoaded', function() {
  document.getElementById('pre').textContent = foo;
});
<pre id="pre"></pre>

Is there a way to update the contents as desired?

Sᴀᴍ Onᴇᴌᴀ
  • 8,218
  • 8
  • 36
  • 58

2 Answers2

2

You seem to have misunderstood the answer you linked to. The answer states:

If you wish to have a string which spans multiple lines, you may insert a backslash character '\' just before you terminate the line, like so:

//Perfectly valid code
var foo = "Bob \
is \
cool.";

However that string will not contain \n characters in the positions where the string was broken into separate lines. The only way to insert a newline into a string is to insert a character with a value of 10, the easiest way of which is the \n escape character.

var foo = "Bob\nis\ncool.";

So this is what you should be doing instead:

//Perfectly valid code
var foo = "Bob\nis\ncool.";
document.addEventListener('DOMContentLoaded', function() {
  document.getElementById('pre').textContent = foo;
});
<pre id="pre"></pre>

If you want both to break the string into multiple lines and to have newlines within the string, you need both:

//Perfectly valid code
var foo = "Bob\n\
is\n\
cool.";
document.addEventListener('DOMContentLoaded', function() {
  document.getElementById('pre').textContent = foo;
});
<pre id="pre"></pre>
Community
  • 1
  • 1
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
1

Another way to do it is to use template literals.

// template literal syntax
var foo = `Bob 
is 
cool.`;
document.addEventListener('DOMContentLoaded', function() {
  document.getElementById('pre').textContent = foo;
});
<pre id="pre"></pre>
DonovanM
  • 1,174
  • 1
  • 12
  • 17