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

397
Vistas
Rendering tabs and other special characters as is in JSX

I need to render a string exactly as I get it from the server, for example if I get a string that contains "\t" I need it to be rendered as "\t" and not as space/s. In the state of the component I see that the string appears with the special characters but rendered without:

state: '\"id\"\t\"name\n key\"'

what is rendered: "id" "name key"

How can I prevent this from happening?

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Since JS and DOM by default parse special characters such as \n, you can define special characters that you want to prevent from behaving in their default way and replace them with original plus backslash before it:

Take a look at this runnable snippet:

let textWithSpecialChars = `"id"\t"name\n key\f \r \b"`;

const specialChars = ['\\b', '\\r', '\\f', '\\n', '\\t'];

let modifiedTextWithSpecialChars = JSON.stringify(textWithSpecialChars);

specialChars.forEach((char) => {
  modifiedTextWithSpecialChars = modifiedTextWithSpecialChars.replace(char, '\\' + char);
});

console.log(modifiedTextWithSpecialChars); 
// "\"id\"\\t\"name\\n key\\f \\r \\b\""

console.log(JSON.parse(modifiedTextWithSpecialChars));
// "id"\t"name\n key\f \r \b"

console.log(textWithSpecialChars);
// "id" "name
// key 
// "


document.body.innerHTML = JSON.parse(modifiedTextWithSpecialChars)

Analysis

  1. You collect all special characters in that array and escape them.
  2. Stringify your string, in this way you can use that string in JS without JS parsing special characters
  3. Take this string and loop through all special characters that you added above
  4. For every special character take the original string and replace special character such as \n with \\n. Return that value to modifying string and continue until all special characters are replaced. Stringified result of this will be '\"id\"\\t\"name\\n key\\f \\r \\b\"'
  5. Parse your string back and JS will not parse special characters as special characters, rathe they will be plain strings.
over 4 years ago · Santiago Trujillo 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