Convert HTML to plain text in contentEditable

2020-06-01 03:46发布

问题:

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 in there, and copy the value. Pretty much the answer from here. The problem is that I can’t do this:

$("#paste-output").text($("#area").val());

because that would replace my entire content with the pasted text. So I need to paste the content at caret position. I put together a script that does that:

pasteHtmlAtCaret($("#area").val());

// pastes CTRL+V content at caret position
function pasteHtmlAtCaret(html) {
  var sel, range;
  if (window.getSelection) {
    sel = window.getSelection();
    if (sel.getRangeAt && sel.rangeCount) {
      range = sel.getRangeAt(0);
      range.deleteContents();
      var el = document.createElement("div");
      el.innerHTML = html;
      var frag = document.createDocumentFragment(), node, lastNode;
      while ((node = el.firstChild)) {
        lastNode = frag.appendChild(node);
      }
      range.insertNode(frag);

      if (lastNode) {
        range = range.cloneRange();
        range.setStartAfter(lastNode);
        range.collapse(true);
        sel.removeAllRanges();
        sel.addRange(range);
      }
    }
  } else if (document.selection && document.selection.type != "Control") {
    document.selection.createRange().pasteHTML(html);
  }
}

The only problem is that it pastes HTML content, at caret position using the html variable. How can I transform that into plain text? I tried adding the jQuery .text(html) to variable without luck. Something like this might help:

el.textContent||el.innerText;

Any ideas or a better solution? Thanks!


EDIT: Thanks to the answers below 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() {
    var text = $('<div>').html($("#area").val()).text();
    pasteHtmlAtCaret(text);
  }, 20);
});

回答1:

  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.


回答2:

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


回答3:

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, '');
}


回答4:

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.