This is about retaining literal data in HTML via js writes in a browser.
Sample code…when I display this in Javascript, using document.write
:
<html>
<script>
FULL = `
{
"key": "something",
"value": "{n "theId": "our_id"}",
"futureData": "{"myEvent":"\"UNCHANGED\"","myEventTimestamp":"\"2023-03-16T14:44:36.639\""}"
}
`
;
document.write('<pre>'+FULL+'</pre>');
</script>
</html>
In HTML, even if I wrap it around with <pre>
it loses the slashes and messes around with the new line character, etc. How can I ensure the document.write
does NOT lose the slashes and newline, and shows the data exactly as it’s in the codes? This is what it looks like:
{
"key": "something",
"value": "{
"cdrId": "our_id"}",
"futureData": "{"myEvent":""UNCHANGED"","myEventTimestamp":""2023-03-16T14:44:36.639""}"
}
Some slashes are gone.. the newline character is gone.
Any ideas on how to retain the text with JS when printing in HTML? The way the code block does here on this website!
2
Answers
You can use JavaScript’s
decodeURIComponent()
function to achieve this.The
escape()
function encodes special characters, preserving the newlines and backslashes in your JSON string anddecodeURIComponent()
is used to decode the escaped characters and get the original content back.In comments you write:
The answer is, yes, using the
String.raw
tag function. Note however, that substitutions, like${foo}
are still supported. If you don’t want that either, then you need to escape those.As to escaping characters for HTML, there are really only the characters "&" and "<" that (sometimes) need to be escaped. So you could do this:
Note that the "problem" you encountered has nothing to do with
document.write
or HTML rendering. The string given todocument.write
didn’t have the "lost" backslashes, sodocument.write
faithfully rendered what you gave to it. If you would have usedconsole.log
instead ofdocument.write
you would also have seen that yourFULL
string variable didn’t have those backslashes.Realise that the string literal notation in your assignment to
FULL
involves escaping itself! Backslash has a special meaning in a string literal, and so you never really have them in your string from the outset. WithString.raw
you can eliminate this special behaviour of backslashes, but this has little practical use, since you would typically get the string from elsewhere (user input, http response, …).