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

176
Visualizações
Javascript: read alert message from file and display with line break

How can I in Javascript read strings from a textfile and display them in an alert box with newlines?

Suppose I have an ASCII textfile "messages.txt" containing two lines:

AAA\nBBB\nCCC
DDD\nEEE\nFFF

In javascript, I read the file content and store it in a variable "m":

    var m;
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function ()
      { if ((xmlhttp.readyState==4) && (xmlhttp.status==200 || xmlhttp.status==0))
        { m = xmlhttp.responseText.split('\n'); };
      };
    xmlhttp.open("GET", "messages.txt", false);
    xmlhttp.send(null);

Now when I display the first message with

console.log(m[0]);
alert(m[0]);

it is shown exactly as in the textfile and with no line breaks; i.e

AAA\nBBB\nCCC

and not as

AAA
BBB
CCC

Changing \n to \\n, \r\n, \\r\\n or %0D%0A in the textfile doesn't help; the alert is still displayed as one line including the escape characters without replacing them by newline. Changing the encoding of "messages.txt" from ASCII to UTF-8 didn't help either.

To clarify the problem: When m is read from the file "message.txt", it is split into an array of strings. m[0] equal to "AAA\nBBB\nCCC".

console.log(m[0]);                  // displays AAA\nBBB\nCCC
console.log('AAA\nBBB\nCCC');       // displays AAA
                                    //          BBB
                                    //          CCC

console.log(typeof(m[0])            // displays string
console.log(m[0]=="AAA\nBBB\nCCC"); // displays false

Why is m[0] not equal to "AAA\nBBB\nCCC" (even if exactly this is what is displayed in the console)? I guess, that is the reason why no line breaks appear.

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

0

Single quotes don't interpret newline breaks (\n). So, you need to change the quotes in your split() method to have double quotes.

Use the split() function like so.

const str = "Hi! I'm text!\nIsn't this supposed to be newline?";

console.log(str.split("\n"));

This should return an array like so when run.

[
  "Hi! I'm text!",
  "Isn't this supposed to be newline?"
]

This is how to separate your text with line breaks.


For more information, see this other Stack Overflow question.

about 4 years ago · Juan Pablo Isaza Relatório

0

you need to add another \ at split('\n') to be split('\\n')

or change the single quote to douple quotes split("\n")

also i encourage you to read this quick article about 'Single' vs "Double" quotes

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