The problem is where this returned string will be processed.
\n , \r , \t etc. - all JavaScript string escape codes and, as such, they will only work when the string is evaluated by the JavaScript runtime. If you have a JavaScript string containing these codes and passing this string to an HTML parser (for example, via .innerHTML ), then the HTML parser will ask you to evaluate this string in the HTML parser world as well <br> how to add a string, not \n . That is why <br> working for you.
So, when \n is evaluated by the JavaScript engine, a newline character is entered into the string, but when the HTML parser receives this newline character, it simply ignores it, as it would with any carriage return in the markup.
In the old days, we could get this βprettyβ code by typing it with document.writeln() , which will write your content, and then add the line feed to the HTML. You can still do it today, but this is not considered good practice because it requires you to embed the code inside the HTML document, otherwise you will overwrite the entire DOM.
If this is what you just want, because it will make you feel warm and fuzzy, I would recommend forgetting about it and moving on.
Finally, here is the standard DOM method for creating new elements and entering them in the DOM:
var o = document.getElementById("output"); var scriptContent = "alert('Hello World!')"; var s = document.createElement("script"); var t = document.createTextNode(scriptContent); s.appendChild(t); o.appendChild(s);
<div id="output"> </div>
source share