Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

122
Visualizações
How do I prevent HTML from ignoring the newline that comes from JavaScript?

I'd like to write my own hackertyper site that prints itself when pressing some keys.

But when I try the code below, it prints everything at the same line. I used template literals (``) and couldn't make it. Then tried <br /> in the string but also not worked. How do I make it right?

Edit: I was using <p> tag in the HTML file, when I changed it to <pre> tag as Praveen said, it solved my problem. Thank you.

"use strict";

let str = `"use strict"

let str = "";

let emptyStr = "";
let i = 0;
document.addEventListener("keydown", function () {
  emptyStr += str.charAt(i++) + str.charAt(i++) + str.charAt(i++);
  document.querySelector("#string").textContent = emptyStr;
});`;

let emptyStr = "";
let i = 0;
document.addEventListener("keydown", function () {
  emptyStr += str.charAt(i++) + str.charAt(i++) + str.charAt(i++);
  document.querySelector("#string").textContent = emptyStr;
});
<p id="string"></p>

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I guess if you're trying to print it out, you need to print it out on a <pre> tag or an element with style white-space: pre or similar.

Here's an example with <pre> tag:

let str = `This is HackerTyper

See I have   spaces and lines!`;

let emptyStr = "";

let i = 0;
document.addEventListener("keydown", function () {
  emptyStr += str.charAt(i++) + str.charAt(i++) + str.charAt(i++);
  document.querySelector("#string").textContent = emptyStr;
});
<pre id="string"></pre>

Here's the same with white-space: pre for <div>:

let str = `This is HackerTyper

See I have   spaces and lines!`;

let emptyStr = "";

let i = 0;
document.addEventListener("keydown", function () {
  emptyStr += str.charAt(i++) + str.charAt(i++) + str.charAt(i++);
  document.querySelector("#string").textContent = emptyStr;
});
div {
  white-space: pre;
}
<div id="string"></div>

And, finally, just wanted to tell, this is a really good implementation of HackerTyper.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda