用于最小化 CSS 的正则表达式
我有一个用 node.js 编写的海峡前向聚合器/最小化器/缓存器。现在效果很好。
然而,我想知道是否有任何方法可以改进我的最小化正则表达式调用。有些注释并没有完全从 CSS 中剥离出来,而且我还注意到一些其他的问题。
另外,考虑到我使用正则表达式的能力,我也许可以在一半的调用中完成同样的事情。 :)
任何建议将不胜感激。
谢谢。
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;
}
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
应该更清晰一点,避免重复。第一次替换后,就只剩下空格了;第二次替换后,只有单个空格。这使得接下来的替换变得更加容易。
解释注释删除正则表达式(此处显示为不带分隔符的纯详细正则表达式):
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):