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?
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)
\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\"'