0

Is there an easy way to convert HTML code, that is structured in a certain way, to a single string (that can then be used in a Javascript variable). The new lines and tabs in the html code need to be converted to \n and \t so that the formatting can stay in tact.

example HTML:

<html>
    <head>
         <title>Hello World</title>
    </head>
    <body>
        <h1>Title</h1>
            <h2>Subtitle</h2>
                <p>Some text goes here</p>
    </body>
 </html>

I've converted this manually to this:

<html>\n\n\t<head>\n\t\t <title>Hello World</title>\n \t</head>\n\n \t<body>\n \t\t<h1>Title</h1>\n \t\t\t<h2>Subtitle</h2>\n \t\t\t\t<p>Some text goes here</p>\n \t</body>\n\n </html>\n

Is there an easy way to do this automatically? Because I need to convert larger chunks of HTML to this format. Thanks.

jibly
  • 115
  • 1
  • 13
  • 1
    What backend languages do you have at your disposal? – MyStream May 27 '15 at 06:18
  • I was hoping there is a converter somewhere that lets me paste the HTML code and convert it to that type of string. If not, i'll make sure I get the right backend languages in place because this conversion will have to happen any way. – jibly May 27 '15 at 06:20
  • Possible duplicate of two questions [this](http://stackoverflow.com/questions/13532761/javascript-find-and-replace-line-breaks) and [this](http://stackoverflow.com/questions/4562756/replacing-tab-characters-in-javascript) – Abozanona May 27 '15 at 06:21
  • realized I had to re-formulate the question entirely but wasn't able to delete the previous one. – jibly May 27 '15 at 06:22

2 Answers2

1
    function format(data) {
        var returnStr = "";
        var lines = data.split("\n");
        var block = [];
        for (var i = 0; i < lines.length; i++) {
            block = lines[i].split('\t');
            for (var j = 0; j < block.length; j++) {
                returnStr += block[j];
                if (block.length>1) {
                    returnStr +=  "\\t";
                }
            };
            returnStr +=  "\\n";
        };
        return returnStr;
    }
dswwsd
  • 133
  • 5
0

If you are doing this to show new line and return carriage in html, then you don't need to do it explicitly. You can do it in css by setting the white-space attribute pre-line value.

<span style="white-space: pre-line">CommentText</span>
Denny John
  • 464
  • 7
  • 20