简体   繁体   中英

Convert InnerHTML to human readable code

I'm writing a code to take the html code from a div and put it into a text box for editing. If I just take the code and directly print it I get:

<h1>hi</h1><p>Sloppy long one line</p><p>and so on</p>

This is hard to read so I want it like this:

<h1>
hi
</h1>
<p>
Sloppy long one line
</p>
<p>
and so on
</p>

I have this:

function add_code()
{
    var html= document.getElementById("body_visual_editor").innerHTML //Gets the code
    html= html.replace(/draggable="true"/g, ''); //Removes the draggable attributes that are added to the elements when returning the code to the div 
    html= html.replace(/id="autoid[0-9]+"/g, ''); ////Removes the auto generated ID's that are added to the elements when returning the code to the div
    html= html.replace(/</g, '\n<'); //Adds a line break before tags
    html= html.replace(/\n\n/g, '\n'); //Fixes glitch caused by previous line
    html= html.replace(/>(?!\n)/g, '>\n'); //Adds line break after tag
    document.getElementById("body_code_box").value= html.trim(); //Adds the code to the textarea for editing.
}

The issues with it:

when I remove the draggable attributes it leaves 2 spaces at the end of the tag.

when I add the line break before the tags it adds extra line breaks even if there is already one, so I need the html= html.replace(/\\n\\n/g, '\\n') to remove it.

That fix leaves an extra line break at the beginning of the code so I need the trim to remove it.

It works but seems very sloppy. Is there a better way to write this to be more streamlined and effective? No JQuery please.

Ok. I think I understand what you want.

var text = document.getElementById("yourDiv").innerHTML;
var find = '<';
var re = new RegExp(find, 'g');
text = text.replace(re, '\n<');
find = '>';
var re = new RegExp(find, 'g');
text = text.replace(re, '>\n');

Here is a JSFiddle

Strange that this was never answered properly. All that needs to be done is to replace the HTML Characters with their relative Entity name.

Like so (Run the snippet to see it in action):

 let text = document.getElementById('raw').innerHTML, find = '<', re = new RegExp(find, 'g'); text = text.replace(re, '&lt;'); find = '>'; re = new RegExp(find, 'g'); text = text.replace(re, '&gt;'); document.getElementById('CodeOut').innerHTML = text;
 <section id="raw"> <h1>hi</h1><p>Sloppy long one line</p><p>and so on</p> </section> <section id="Code" style="background-color:grey;color:#fff;padding:10px;"> <pre><code id="CodeOut"></code></pre> </section>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM