在保留换行符(使用JavaScript)的同时将HTML转换为纯文本最方便的方法是什么?

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

演示:http://jsfiddle.net/wv49v/

码:

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)

  • @ hienbt88:它肯定建立在摇摇欲坠的基础之上:Selection.toString()不是标准化的,在浏览器之间的工作方式不同,并且不保留IE 9中的换行符(自该答案的原始版本编写以来发布).但是,它仍然保留了当前版本的Mozilla,WebKit和Opera中的换行符,并且因为我刚刚调整它,IE.老实说,我不会长期推荐这种方法. (2认同)

chr*_*cpn 7

我根据这个答案做了一个函数: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)


Kev*_*kia 5

我试图找到我为此写的一些代码。效果很好。让我概述一下它的作用,并希望您可以复制它的行为。

  • 用替代文字或标题文字替换图像。
  • 将链接替换为“文本[链接]”
  • 替换通常会产生垂直空白的东西。h1-h6,div,p,br,hr等(我知道,我知道。这些实际上可以是内联元素,但效果很好。)
  • 去除其余标签,并替换为空字符串。

您甚至可以进一步扩展它来格式化诸如有序列表和无序列表之类的内容。这实际上取决于您要走多远。

编辑

找到了代码!

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)

  • 语言真的无关紧要,它是如何进行的。这很容易移植到JS。我只是在展示我过去所做的事情。 (2认同)