Welcome to the Question2Answer Q&A. There's also a demo if you just want to try it out.
+1 vote
3.5k views
in Plugins by
edited by

Note: I know about the discussions on never user regex to clean html, but it works for many cases. In my opinion it makes sense for CKEditor .

This might be helpful for one or the other:

CKEDITOR.on('instanceReady', function(ev){
    ev.editor.on('paste', function(evt) {    
        if(typeof(evt.data['html']) !== 'undefined' && evt.data['html'] != null) {
            //remove all html tags but whitelisted tags
            evt.data['html'] = (evt.data['html']).replace(/<(?!\/?(p|br|ul|li|b|i|sub|sup|strike|em|strong|span|table|caption|tbody|tr|td)(>|\s))[^<]+?>/g, '');
            // remove font-family, font-size, line-height from style
            evt.data['html'] = (evt.data['html']).replace(/font-family\:[^;]+;?|font-size\:[^;]+;?|line-height\:[^;]+;?/g, '');
            // remove if style is empty, e.g. style="" || style="   "
            evt.data['html'] = (evt.data['html']).replace(/style\="\s*?"/, '');
            // remove empty tags, e.g. <p></p>
            evt.data['html'] = (evt.data['html']).replace(/<[^\/>][^>]*><\/[^>]+>/, '');
            
            //remove all styles from tags
            //evt.data['html'] = (evt.data['html']).replace(/(<[^>]+) style=".*?"/i, '');
        }
    }, null, null, 9);

}

 

The comments explain each line.

 

Example:

<p style="line-height:200%;color:#FF0000;">this is good</p> <p></p> <script>js code</script>

becomes:

<p style="color:#FF0000;">this is good</p>

 

Of course, this is client-side and not to rely on. Security happens on server-side. This is why I asked about server-side sanitizations.

by
edited by
If you want to clean class and id attributes from tags, add:

// remove id and class attributes
evt.data['html'] = (evt.data['html']).replace(/\s(id|class)="[^"]+"/gi, '');
by
where do i place this code ?
by
you can place the code in any js file that is loaded by q2a. For instance, I am using qa-content/qa-page.js

There you add the jquery ready and the code above:

$(document).ready(function(){
  // ... code above
});

Please log in or register to answer this question.

...