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