<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta charset="utf-8" /> <title>HTML 编码</title> </head> <body> <textarea rows="9" style="width:99%" placeholder="粘贴 HTML 内容" ></textarea> <button class="btn-regex">regex</button> <button class="btn-html">html</button> <p><a target="_blank" href="https://stackoverflow.com/questions/18749591">SO#18749591</a></p> <pre class="view-html"></pre> </body> </html>
var domTxt = document.querySelector('textarea'); domTxt.value = document.documentElement.outerHTML; var domView = document.querySelector('.view-html'); document.querySelector('.btn-html').addEventListener('click', () => { console.time(); var div = document.createElement("div"); div.innerText = domTxt.value; domTxt.value = div.innerHTML.replaceAll('<br>', '\r\n') domView.innerHTML = domTxt.value; console.timeEnd(); }) document.querySelector('.btn-regex').addEventListener('click', () => { console.time(); domTxt.value = domTxt.value.replace(/[\u00A0-\u9999<>\&]/g, function (i) { return '&#' + i.charCodeAt(0) + ';'; }) domView.innerHTML = domTxt.value; console.timeEnd(); })