1

I am making a terminal app in javascript. But the problem is that I can't use innerHTML method. I tried using innerText method, but it doesnt apply multi space and & nbsp; is also ignore. For example:

example.innerText = "a  b"; //output is not 'a  b'

I would be glab if someone could help me.

Saneesh
  • 45
  • 5
  • Does this answer your question? [innerText property is not encoding the html](https://stackoverflow.com/questions/30426903/innertext-property-is-not-encoding-the-html) – Jonathan Nov 09 '22 at 15:39
  • Perhaps this link will enlighten you. https://dirask.com/posts/JavaScript-no-break-non-breaking-space-in-string-jMwzxD – Robin Webb Nov 09 '22 at 15:43
  • In your example you can also just add normal spaces. – HackerFrosch Nov 09 '22 at 15:43
  • But why use two non-breaking spaces instead of using CSS? If you're writing a terminal app, pretty sure you _need_ `white-space: pre` already anyway, to make sure that any whitespace sequence doesn't get collapsed to a single space, or even nothing? With `pre` active, you don't need non-breaking spacing, normal spaces work fine. – Mike 'Pomax' Kamermans Nov 09 '22 at 15:52

3 Answers3

1

example.textContent = 'This\u00a0 thing'

Or

example.textContent = 'This\u00a0\u00a0thing'

dangarfield
  • 2,210
  • 1
  • 13
  • 18
1

  works for HTML, but not for text. .innerText deals with visible text while .textContent recognizes visible and hidden text, see this answer for details.

document.querySelector(".test").textContent = "A\u00A0\u00A0B";
<p>AB</p>
<p class="test"></p>
zer00ne
  • 41,936
  • 6
  • 41
  • 68
1

Why use non-breaking spaces when you can use CSS and normal spaces? If you're writing a terminal app, pretty sure you need white-space: pre already anyway since you're probably using a monospace font and use spaces to align ouput, so just keep using that:

.preeformatted { white-space: pre; }
code { background: #DDD; font-variant: small-caps; font-weight: bold; }
<p class="preeformatted">let's use spaces instead of <code>&amp;nbsp;</code>:   a    b</p>
Mike 'Pomax' Kamermans
  • 49,297
  • 16
  • 112
  • 153