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

316
Visualizações
Print new line character as string in javascript

I'm working on a project which deals with strings a lot. I need to show what kind of delimiter is used in strings. I get that value from an API call. How do I print the delimiter to the console?

delimiter = '\n';

I want to print this on screen.

console.log(delimiter);
// prints "
          "

I need it to print \n instead of literally printing newline.

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

0

The character \n is an escape sequence used for new lines.

That is why you need to use replace on the string if you want to see it in the console. Like so:

console.log(delimiter.replace('\n', '\\n'));

The extra backslash escapes the \n so it is not longer treated as a newline.

More about escape sequences can be found here:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#escape_sequences

about 4 years ago · Juan Pablo Isaza Relatório

0

Using JSON.stringify() you can transform an actual new line character (whatever it might be) into its stringified version. Then after stripping leading and trailing double quotes, you'll get what you're after:

console.log(JSON.stringify(delimiter).replaceAll('"',''));

Update:

How to handle double quotes and control characters inside strings that are delimited with newlines?

This should do the trick:

const delimiter = '\n';
const delimitedText = 'a\nb\nc\nd';
const stringifiedDelimiter = JSON.stringify(delimiter).replaceAll('"','');
console.log(delimitedText.replaceAll(delimiter, stringifiedDelimiter));
about 4 years ago · Juan Pablo Isaza Relatório

0

To display a (multi)line with already wrapped text, use this 🙂

There is a little regex thing, which removes \r and \n

const server = 'a\na';

const client = server.replace(/\r?\n/gm, '\\n');

console.log(1, server);
console.log(2, client);

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