Convert HTML to plain text in contentEditable

后端 未结 4 1873
忘了有多久
忘了有多久 2021-02-07 07:10

I have a contentEditable and I strip the formatting of pasted content on(\'paste\') by catching the event. Then I focus a textarea, paste the content i

相关标签:
4条回答
  • 2021-02-07 07:50
    1. Create an external div,
    2. Put your html in that div,
    3. Copy the text from that div
    4. Insert it at the cursor's position.
    0 讨论(0)
  • 2021-02-07 07:54

    The solution I used is to set the innerText of the element on blur:

    $element.on('blur', () => this.innerText = this.innerText);

    This keeps the whitespace, but strips the formatting. It may work acceptable in your scenario as well.

    0 讨论(0)
  • 2021-02-07 07:55

    Replace tag solution:

    http://jsfiddle.net/tomwan/cbp1u2cx/1/

    var $plainText = $("#plainText");
    var $linkOnly = $("#linkOnly");
    var $html = $("#html");
    
    $plainText.on('paste', function (e) {
        window.setTimeout(function () {
            $plainText.html(removeAllTags(replaceStyleAttr($plainText.html())));
        }, 0);
    });
    
    $linkOnly.on('paste', function (e) {
        window.setTimeout(function () {
            $linkOnly.html(removeTagsExcludeA(replaceStyleAttr($linkOnly.html())));
        }, 0);
    });
    
    function replaceStyleAttr (str) {
        return str.replace(/(<[\w\W]*?)(style)([\w\W]*?>)/g, function (a, b, c, d) {
            return b + 'style_replace' + d;
        });
    }
    
    function removeTagsExcludeA (str) {
        return str.replace(/<\/?((?!a)(\w+))\s*[\w\W]*?>/g, '');
    }
    
    function removeAllTags (str) {
        return str.replace(/<\/?(\w+)\s*[\w\W]*?>/g, '');
    }
    
    0 讨论(0)
  • 2021-02-07 08:09

    Upon request from Jonathan Hobbs I am posting this as the answer. Thanks to the answers above I modified my code and solved the issue. I basically copied the value of textarea into a div and grabbed only its .text():

    // on paste, strip clipboard from HTML tags if any
    $('#post_title, #post_content').on("paste", function() {
      setTimeout(function(){
        var text = $('<div>').html($("#area").val()).text();
        pasteHtmlAtCaret(text);
      }, 20);
    });
    
    0 讨论(0)
提交回复
热议问题