Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegEx to minimize CSS

I have a strait forward aggregator/minimizer/cacher I've written in node.js. It works quite well now.

I am however wondering if there is any way to improve my minimizing regex calls. Some comments are not striped from the CSS entirely, and I notice a few other hiccups here and there.

Also, considering my abilities with regex, I might be able to do the same in half the calls. :)

Any suggestions will be greatly appreciated.

Thanks.

function minimizeData( _content ) {
    var content = _content;
    content = content.replace( /(\/\*.*\*\/)|(\n|\r)+|\t*/g, '' );
    content = content.replace( /\s{2,}/g, ' ' );
    content = content.replace( /(\s)*:(\s)*/g, ':' );
    content = content.replace( /(\s)+\./g, ' .' );
    content = content.replace( /(\s|\n|\r)*\{(\s|\n|\r)*/g, '{' );
    content = content.replace( /(\s|\n|\r)*\}(\s|\n|\r)*/g, '}' );
    content = content.replace( /;(\s)+/g, ';' );
    content = content.replace( /,(\s)+/g, ',' );
    content = content.replace( /(\s)+!/g, '!' );
    return content;
}
like image 462
Spot Avatar asked Dec 09 '10 19:12

Spot


1 Answers

function minimizeData( _content ) {
    var content = _content;
    content = content.replace( /\/\*(?:(?!\*\/)[\s\S])*\*\/|[\r\n\t]+/g, '' );
    // now all comments, newlines and tabs have been removed
    content = content.replace( / {2,}/g, ' ' );
    // now there are no more than single adjacent spaces left
    // now unnecessary: content = content.replace( /(\s)+\./g, ' .' );
    content = content.replace( / ([{:}]) /g, '$1' );
    content = content.replace( /([;,]) /g, '$1' );
    content = content.replace( / !/g, '!' );
    return content;
}

should be a bit clearer and avoids repetition. After the first replace, there will only be spaces left; after the second replace, only single spaces. This makes the following replaces easier.

To explain the comment-removing regex (shown here as a pure verbose regex without delimiters):

/\*       # Match /*
(?:       # Match (any number of times)...
 (?!\*/)  # ... as long as we're not right before a */:
 [\s\S]   # any character (whitespace or non-whitespace).
)*        # (End of repeated non-capturing group)
\*/       # Match */
like image 161
Tim Pietzcker Avatar answered Sep 28 '22 03:09

Tim Pietzcker