Display formatted raw html with jquery

I have a place where I am trying to show code in a text area. I have dumbed down the example but basically user can input some fields, click a button, and the code snippet displays in a text area below for them to edit if they want and then copy.

I finally got it working to display the actual code snippet. But now I can't seem to find a way to format it so that it is indented and looks nice.

var mySnippet =
"<div id=\"myOuterDiv\">"
    + "<div id=\"myInnerDiv\">"
    + "</div>"
    + "</div>";

Which displays in my text area like so.

<div id="myOuterDiv"><div id="myInnerDiv"></div></div>

Where as I would like to see it as:

    <div id="myOuterDiv">
        <div id="myInnerDiv">

I'd really like to avoid any 3rd party plugins as its for work an a pain to get approval. It's just 4 small snippets I need to format.

UPDATE This appears to work as I need.

var mySnippet =
        "<div id=\"myOuterDiv\">\r"
            + "    <div id=\"myInnerDiv\">\r"
            + "    </div>\r"
            + "</div>\r";


<div id="myOuterDiv">
    <div id="myInnerDiv">



Add a \n if you want a new line like

var mySnippet = "<div id=\"myOuterDiv\">\n"
    + "<div id=\"myInnerDiv\">\n"
    + "</div>\n"
    + "</div>\n";

Single character escape sequences:

\b: backspace (U+0008 BACKSPACE)
\f: form feed (U+000C FORM FEED)
\n: line feed (U+000A LINE FEED)
\r: carriage return (U+000D CARRIAGE RETURN)
\t: horizontal tab (U+0009 CHARACTER TABULATION)
\v: vertical tab (U+000B LINE TABULATION)
\0: null character (U+0000 NULL)

Example: http://jsfiddle.net/jtx7e/


just use <pre id="mySnippetArea"></pre> and add \n and space according to the needed layout


you can also write

var mySnippet =
"<div id=\"myOuterDiv\">\n\
   <div id=\"myInnerDiv\">\n\


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.