Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep line breaks on pasting with 'text/plain'?

EDIT : NOT A DUPLICATE

Infact, the question marked as duplicate was even mentioned and linked here. The titles and purposes of the questions are completely different from each other. One of the answers of the other question, that could arguibly be used to answer this one, is there for a completely different reason (compatibility with IE) and could hardly be understood as an answer to this question.


ORIGINAL QUESTION

I got the following code from this Javascript trick for 'paste as plain text` in execCommand

I works as intended. It gives me plain text.

But while I would like to get rid of all text formatting, I would like to keep only the line breaks of the copied text? Is there a way to fix this code to achieve this behavior?

NOTE: As an example, it seems that the question editor where we write our question here on Stack Overflow works exactly like that. Gets rid of everything but the line breaks are respected.

// ALLOW TEXT ONLY ON PASTE
  function onPaste(e) {
    e.preventDefault();
    // GET TEXT REPRESENTATION OF CLIBOARD DATA
    const text = (e.originalEvent || e).clipboardData.getData('text/plain');
    // INSERT TEXT MANUALLY
    document.execCommand("insertHTML", false, text);
  }

SNIPPET

function onPaste(e) {
    e.preventDefault();
    // GET TEXT REPRESENTATION OF CLIBOARD DATA
    const text = (e.originalEvent || e).clipboardData.getData('text/plain');
    // INSERT TEXT MANUALLY
    document.execCommand("insertHTML", false, text);
}

document.getElementById("root").addEventListener("paste", onPaste);
#root {
  border: 1px dotted blue;
  
}
<div>Below is a contenteditable DIV</div>
<div id="root" contenteditable>

</div>

<div><br><br>Copy both paragraphs to the contenteditable div</div>
<p>First <b>Paragraph</b></p>
<p>Second Paragraph</p>
like image 355
cbdeveloper Avatar asked Mar 04 '23 03:03

cbdeveloper


1 Answers

Use the command insertText instead of the command insertHTML.

like image 186
NineBerry Avatar answered Mar 12 '23 11:03

NineBerry