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

201
Visualizações
How can I avoid control character interpretation in Javascript template string interpolation?

I have a string variable containing a control character (newline). I want to output that variable but with the control character as its literal representation and not interpreted:

console.log(`Using "${nl}" as newline`)

where the nl variable may contain one of \n, \r, or \r\n. The output of this is of course

Using
as newline

but it should be e.g.

Using "\r\n" as newline

I guess I somehow need to construct a string like this

console.log('Using "\\r\\n" as newline')

So I've been trying to escape the backslashes in nl by prepending another backslash using nl.replace() but that doesn't seem to work because the nl variable doesn't actually contain any backslash characters.

Is there a way to do this generically, i.e. without coding explicitly for \n, \r, and \r\n?

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

0

You could remove the double quotes, and use JSON.stringify which also produces those quotes, and which encodes newline characters (and more, such as TAB, BS, FF, and escapes double quote and backslash):

let nl = "\r\n";
console.log(`Using ${JSON.stringify(nl)} as newline`);

// Or with a newline in a template literal:

nl = `
`;
console.log(`Using ${JSON.stringify(nl)} as newline`);

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