What is the most convenient way to convert HTML to plain text while preserving line breaks (with JavaScript)?

前端 未结 5 1960
长发绾君心
长发绾君心 2020-12-10 04:24

Basically I just need the effect of copying that HTML from browser window and pasting it in a textarea element.

For example I want this:

Som

5条回答
  •  执笔经年
    2020-12-10 04:59

    If that HTML is visible within your web page, you could do it with the user selection (or just a TextRange in IE). This does preserve line breaks, if not necessarily leading and trailing white space.

    UPDATE 10 December 2012

    However, the toString() method of Selection objects is not yet standardized and works inconsistently between browsers, so this approach is based on shaky ground and I don't recommend using it now. I would delete this answer if it weren't accepted.

    Demo: http://jsfiddle.net/wv49v/

    Code:

    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;
    }
    

提交回复
热议问题