如何在例外的javascript中删除所有html标签?

Cod*_*key 4 javascript regex

我现在最长时间一直在打击这个前锋,我希望有人可以提供帮助.基本上我有一个WYSIWYG字段,用户可以在其中键入格式化文本.但他们当然会复制并粘贴表格/网页等.所以我有一个JS函数捕获粘贴的输入.我有一个功能,将删除文本上的所有格式,这是很好的,但我想让它留下像p和br这样的标签,所以这不仅仅是一个大混乱.

那里有任何正则表达的忍者吗?这是我到目前为止所做的工作.只需要允许标签.

o.node.innerHTML=o.node.innerHTML.replace(/(<([^>]+)>)/ig,"");
Run Code Online (Sandbox Code Playgroud)

bob*_*nce 9

浏览器已经有一个非常好的解析HTML树o.node.将文档内容序列化为HTML(使用innerHTML),尝试使用正则表达式(无法可靠地解析HTML)破解它,然后通过设置innerHTML... 将结果重新解析回文档内容实际上有点不正常.

相反,检查你已经拥有的元素和属性节点o.node,删除你不想要的节点,例如:

filterNodes(o.node, {p: [], br: [], a: ['href']});
Run Code Online (Sandbox Code Playgroud)

定义为:

// Remove elements and attributes that do not meet a whitelist lookup of lowercase element
// name to list of lowercase attribute names.
//
function filterNodes(element, allow) {
    // Recurse into child elements
    //
    Array.fromList(element.childNodes).forEach(function(child) {
        if (child.nodeType===1) {
            filterNodes(child, allow);

            var tag= child.tagName.toLowerCase();
            if (tag in allow) {

                // Remove unwanted attributes
                //
                Array.fromList(child.attributes).forEach(function(attr) {
                    if (allow[tag].indexOf(attr.name.toLowerCase())===-1)
                       child.removeAttributeNode(attr);
                });

            } else {

                // Replace unwanted elements with their contents
                //
                while (child.firstChild)
                    element.insertBefore(child.firstChild, child);
                element.removeChild(child);
            }
        }
    });
}

// ECMAScript Fifth Edition (and JavaScript 1.6) array methods used by `filterNodes`.
// Because not all browsers have these natively yet, bodge in support if missing.
//
if (!('indexOf' in Array.prototype)) {
    Array.prototype.indexOf= function(find, ix /*opt*/) {
        for (var i= ix || 0, n= this.length; i<n; i++)
            if (i in this && this[i]===find)
                return i;
        return -1;
    };
}
if (!('forEach' in Array.prototype)) {
    Array.prototype.forEach= function(action, that /*opt*/) {
        for (var i= 0, n= this.length; i<n; i++)
            if (i in this)
                action.call(that, this[i], i, this);
    };
}

// Utility function used by filterNodes. This is really just `Array.prototype.slice()`
// except that the ECMAScript standard doesn't guarantee we're allowed to call that on
// a host object like a DOM NodeList, boo.
//
Array.fromList= function(list) {
    var array= new Array(list.length);
    for (var i= 0, n= list.length; i<n; i++)
        array[i]= list[i];
    return array;
};
Run Code Online (Sandbox Code Playgroud)