Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

202
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda