Jump to content

User:Anomie/censorship.js

From Wikipedia, the free encyclopedia
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
$( function(){
    if ( !document.createNodeIterator || !window.NodeFilter || !NodeFilter.SHOW_TEXT ) {
        alert( 'The script "User:Anomie/censorship" is not supported on this browser. Offensive words in the page will not be hidden.' );
        $( '#content' ).addClass( 'isCensored' );
        return;
    }

    var iter, node, nextNode, fragment, span;
    var re1 = /^\s*$/;
    var re2 = /^\S+$/;
    var re3 = /(\s*)(\S+|$)/g;
    iter = document.createNodeIterator( document.getElementById( 'content' ), NodeFilter.SHOW_TEXT, function ( node ) {
        var nn = node.parentNode.nodeName.toLowerCase();
        if ( nn === 'textarea' ) {
            return NodeFilter.FILTER_REJECT;
        }
        return NodeFilter.FILTER_ACCEPT;
    }, true );
    node = iter.nextNode();
    while ( node ) {
        nextNode = iter.nextNode();
        if ( re1.test( node.nodeValue ) ) {
            /* Do nothing */
        } else if ( re2.test( node.nodeValue ) ) {
            span = document.createElement( 'span' );
            span.className = 'censored';
            node.parentNode.insertBefore( span, node );
            span.appendChild( node );
        } else {
            fragment = document.createDocumentFragment();
            node.nodeValue.replace( re3, function ( m, space, text ) {
                if ( space.length ) {
                    fragment.appendChild( document.createTextNode( space ) );
                }
                if ( text.length ) {
                    span = document.createElement( 'span' );
                    span.className = 'censored';
                    span.appendChild( document.createTextNode( text ) );
                    fragment.appendChild( span );
                }
            } );
            node.parentNode.replaceChild( fragment, node );
        }
        node = nextNode;
    }
    $( '#content' ).addClass( 'isCensored' );
} );