Search code examples
htmlangularpre

How to insert a line break into a string variable to be displayed in a pre or code tag?


I know that there are lots of questions about line breaks in pre and code tags, but they all seem to concern string literals. However, I want to display a string variable that I get from a HTTP request. The string represents a code snippet and will look like this: console.WriteLine("Hello");\nconsole.WriteLine("World");\nconsole.WriteLine("Bye");\n

My problem is that when I put this into a pre or code tag like this:

<pre>
    {{ code }}
</pre>

it displayes as

console.WriteLine("Hello");\nconsole.WriteLine("World");\nconsole.WriteLine("Bye");\n

instead of

console.WriteLine("Hello");
console.WriteLine("World");
console.WriteLine("Bye");

Replacing \n with <br> also doesn't help, and I didn't have any luck with css settings either. I could in theory change the backend to not put \n at the end of every line, but I have no idea how I would denote a line break then.


Solution

  • Ok so I made it work by calling replaceAll("\\n", "\n") on the code string.