Dan*_*sak 12 html javascript plaintext
基本上我只需要从浏览器窗口复制HTML并将其粘贴到textarea元素中.
例如,我想要这个:
<p>Some</p>
<div>text<br />Some</div>
<div>text</div>
Run Code Online (Sandbox Code Playgroud)
成为这个:
Some
text
Some
text
Run Code Online (Sandbox Code Playgroud)
Tim*_*own 17
如果该HTML在您的网页中可见,您可以使用用户选择(或仅TextRange在IE中)来完成.这确实保留了换行符,如果不一定是前导和尾随空格.
更新2012年12月10日
但是,对象的toString()方法尚未标准化,并且浏览器之间的工作方式不一致,因此这种方法基于不稳定的基础,我不建议现在使用它.如果没有被接受,我会删除这个答案.Selection
码:
function getInnerText(el) {
var sel, range, innerText = "";
if (typeof document.selection != "undefined" && typeof document.body.createTextRange != "undefined") {
range = document.body.createTextRange();
range.moveToElementText(el);
innerText = range.text;
} else if (typeof window.getSelection != "undefined" && typeof document.createRange != "undefined") {
sel = window.getSelection();
sel.selectAllChildren(el);
innerText = "" + sel;
sel.removeAllRanges();
}
return innerText;
}
Run Code Online (Sandbox Code Playgroud)
我根据这个答案做了一个函数:https ://stackoverflow.com/a/42254787/3626940
function htmlToText(html){
//remove code brakes and tabs
html = html.replace(/\n/g, "");
html = html.replace(/\t/g, "");
//keep html brakes and tabs
html = html.replace(/<\/td>/g, "\t");
html = html.replace(/<\/table>/g, "\n");
html = html.replace(/<\/tr>/g, "\n");
html = html.replace(/<\/p>/g, "\n");
html = html.replace(/<\/div>/g, "\n");
html = html.replace(/<\/h>/g, "\n");
html = html.replace(/<br>/g, "\n"); html = html.replace(/<br( )*\/>/g, "\n");
//parse html into text
var dom = (new DOMParser()).parseFromString('<!doctype html><body>' + html, 'text/html');
return dom.body.textContent;
}
Run Code Online (Sandbox Code Playgroud)
我试图找到我为此写的一些代码。效果很好。让我概述一下它的作用,并希望您可以复制它的行为。
您甚至可以进一步扩展它来格式化诸如有序列表和无序列表之类的内容。这实际上取决于您要走多远。
编辑
找到了代码!
public static string Convert(string template)
{
template = Regex.Replace(template, "<img .*?alt=[\"']?([^\"']*)[\"']?.*?/?>", "$1"); /* Use image alt text. */
template = Regex.Replace(template, "<a .*?href=[\"']?([^\"']*)[\"']?.*?>(.*)</a>", "$2 [$1]"); /* Convert links to something useful */
template = Regex.Replace(template, "<(/p|/div|/h\\d|br)\\w?/?>", "\n"); /* Let's try to keep vertical whitespace intact. */
template = Regex.Replace(template, "<[A-Za-z/][^<>]*>", ""); /* Remove the rest of the tags. */
return template;
}
Run Code Online (Sandbox Code Playgroud)