JSFiddle - React, Tailwind, and code Playground

by Tom Wan

HTML

<p>plainText:</p>
<div id="plainText" contenteditable="true"></div>
<p>linkOnly:</p>
<div id="linkOnly" contenteditable="true"></div>
<p>html:</p>
<div id="html" contenteditable="true"></div>

CSS

div {
    width: 80%;
    min-height: 40px;
    border: 1px solid gray;
}
a { color: blue; }

JavaScript

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