Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

398
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!