简体   繁体   中英

How to trim html content in js?

I have a contenteditable div and I would like to remove empty lines and spaces at the beginning and the end before sending his content to server. I have read some answers here but don't find what I want. I would like to do the same as trim function by deleting spaces(as nbsp; ) at the begenning and at the end but also delete empty lines(which mean empty block as <div></div> or <br> or <div><br></div> and so on...)

Here is some examples:

<div><br></div><div>Hello</div><div>World</div><div><br></div></div>

Should be

<div>Hello</div><div>World</div>

And also

&nbsp;<div><br></div><div>Hello</div><div></div><div>World</div>&nbsp;&nbsp;

Should be

<div>Hello</div><div></div><div>World</div>

And so on...

How to do this please ?

Here is what are you looking for, using for loop , innerHTML and outerHTML properties.

 function trimHTML(t) { var between = false; var outHTML = ""; for (var i = 0; i < t.childNodes.length; i++) { var lt = t.childNodes[i]; //console.log(lt.innerHTML) var nowset = false; if (lt.innerHTML != undefined && lt.innerHTML != "" && lt.innerHTML != "<br>") { between = !between; nowset = true; outHTML += lt.outerHTML; } if (between && !nowset) { outHTML += lt.outerHTML; } } return outHTML; } var t = document.querySelector("#t"); var result = document.querySelector("#result"); t.innerHTML = "<div></div><div></div><div><br></div><div>Hello</div><div>World</div><div><br></div></div>"; result.value = "---TEST1: \\nfrom:\\n" + t.innerHTML + "\\nto:\\n" + trimHTML(t); t.innerHTML = "&nbsp;<div><br></div><div>Hello</div><div></div><div>World</div>&nbsp;&nbsp;"; result.value += "\\n---TEST2: \\nfrom:\\n" + t.innerHTML + "\\nto:\\n" + trimHTML(t);
 <div id="t"> </div> <textarea id="result" style="width: 100%;min-height:90px;"> </textarea>

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