Categories
JavaScript Answers

How to paste as plain text in execCommand with JavaScript?

Spread the love

Sometimes, we want to paste as plain text in execCommand with JavaScript.

In this article, we’ll look at how to paste as plain text in execCommand with JavaScript.

How to paste as plain text in execCommand with JavaScript?

To paste as plain text in execCommand with JavaScript, we can insrt plain text with execCommand.

For instance, we write

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

to listen for the paste event on the editor element.

In the paste event handler, we call preventDefault to prevent the default paste action.

Then we get the pasted plain text data with clipboardData.getData with "text/plain".

Finally, we use document.execCommand("insertHTML", false, text); to paste the data we got.

Conclusion

To paste as plain text in execCommand with JavaScript, we can insrt plain text with execCommand.

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 *