TextContent with LineBreak
by Adi Jaya
HTML
<button onclick="__demo();">Run</button>
<div contenteditable="true" id="editor">ad jasda <script src=""></script> 2222222<div><br></div><p>sdfsd fsdfs fdsdfsdfsd <link rel=""/> fsdfsdfsdf sdfsdf sdfsdf sdfsdf sdfsdf sdfsdfsdf</p><div>sdfsdf sdfsdfsdf</div><div><br></div><script id="asd">function _sample1(){}</script><div>sdfsdfsdfsdf</div><div><br></div><div>dfsdf sdfsdfsdfsdfsdfsdf sdfsdfsdf sd <b>BOLD</b> asdasd</div><div><br></div><div>asdasdasd <i>ITALIC</i> asdasdasdasd <u>UNDERLINE</u></div><div><br></div><div>sdf sdfsdf sdfsdf asdasda sdasdasd</div><script>function _sample(){}</script></div>
CSS
[contenteditable] {
padding: 10px;
border: 1px solid silver;
margin-top: 20px;
}
[contenteditable] div {
border: 1px solid blue;
}
[contenteditable] p {
border: 1px solid red;
}
JavaScript
function __demo() {
var editor = document.querySelector("#editor");
var html = editor.innerHTML;
var removeContent = /<(script|style|template)(?:\s[^>]*)?>([\s\S]*?)<\/(script|style|template)>/;
var reg = /<(div|p)(?:\s[^>]*)?>([\s\S]*?)<\/(div|p)>/;
var reg2 = /<[^>]+>/g;
var reg3 = / /g;
html = html.replace(new RegExp( removeContent, 'g'), "");//remove style, script and template tags
html = html.replace(new RegExp(reg, 'g'), "\n$2"); //block element to LineBreak
html = html.replace(reg2, ""); //remove <tags> exp : <b>|</b>|<i>|</i>|<u>|</u> etc.
html = html.replace(reg3, " "); // to whiteSpace
console.log(html);
}