Categories
JavaScript Answers

How to paste as plain text with JavaScript execCommand?

Spread the love

To paste as plain text with JavaScript execCommand, we get the pasted data as plain text before we insert it.

For instance, we write

editor.addEventListener("paste", (e) => {
  e.preventDefault();
  const text = e.clipboardData.getData("text/plain");
  document.execCommand("insertHTML", false, text);
});

to listen to the past event on editor with addEventListener.

In it, we call preventDefault to stop the default paste behavior.

Then we get the pasted text as plain text by calling clipboardData.getData with 'text/plain',

Finally, we call execCommand to insert the text into editor.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *