Sometimes, we want to paste as plain text with execCommand in JavaScript.
In this article, we’ll look at how to paste as plain text with execCommand in JavaScript.
How to paste as plain text with execCommand in JavaScript?
To paste as plain text with execCommand in JavaScript, we listen to the paste event.
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 to the paste event with addEventListener
.
In the event listener, we stop the default paste behavior with preventDefault
.
Then we get the pasted text as plain text with (e.originalEvent ?? e).clipboardData.getData("text/plain")
.
And then we insert the HTML into the element with document.execCommand("insertHTML", false, text);
.
Conclusion
To paste as plain text with execCommand in JavaScript, we listen to the paste event.