如果需要,删除 CSS 选择器及其相关属性
我正在尝试删除特定的 CSS 选择器,并且如果属性列表的选择器没有比脚本删除的选择器多...
我能够使脚本的一部分正常工作: http://jsfiddle.net/jnbdz/MarRr/5/
这是代码:
$$('button')[0].addEvent('click', function(){
var css = document.id('css').get('text');
var newCss = css.replace(/(\n|\r|\s\s)/g, "")
.replace(/(,\s*body\s*(?={)|,\s*body\s*(?=,)|body\s*,|,\s*head\s*(?={)|,\s*head\s*(?=,)|head\s*,)/gi, "")
.replace(/(body\s*(?={)|head\s*(?={))/gi, "")
.replace(/(^\{[^}]*?\}|\}\s*\{[^}]*?\})/gim, "");
document.id('cleancss').set('text', newCss);
});
问题是,如果我删除换行符我编写的脚本无法删除与任何选择器无关的属性...
如果我保留换行符,它就可以工作...
另外,我想从擅长 ReGex 的编码人员那里知道我的代码是否是好...
提前非常感谢您的帮助。
I am trying to remove specific CSS selectors, and if there is no more selectors for a list of properties than the script removes it...
I was able to get a part of the script working: http://jsfiddle.net/jnbdz/MarRr/5/
Here is the code:
$('button')[0].addEvent('click', function(){
var css = document.id('css').get('text');
var newCss = css.replace(/(\n|\r|\s\s)/g, "")
.replace(/(,\s*body\s*(?={)|,\s*body\s*(?=,)|body\s*,|,\s*head\s*(?={)|,\s*head\s*(?=,)|head\s*,)/gi, "")
.replace(/(body\s*(?={)|head\s*(?={))/gi, "")
.replace(/(^\{[^}]*?\}|\}\s*\{[^}]*?\})/gim, "");
document.id('cleancss').set('text', newCss);
});
The problem is that if I remove the line breaks the script I wrote wont be able to remove the properties that are not related to any selectors...
If I keep the line breaks it works...
Also, I would like to know from coders that are good with ReGex if my code is good...
Thanks a lot in advance for any help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在最后一次替换中,您使用了多行标志。如果您只有一行(在第一次替换后执行此操作),则这是行不通的。因此,我们首先保留换行符,并在删除选择器后删除它们。
您还可以稍微简化正则表达式。使用
x(?=a|b)
而不是x(?=a)|x(?=b)
。您也不需要惰性匹配[^\}]*?
。下面是一个工作示例。为了清楚起见,我只删除了
body
选择器。您可以通过删除
{
前面或:
和,
之后的空格来进一步压缩样式表In the last replace you're using the multiline flag. That can't work, if you have only one line, which you do after the first replace. So lets keep the linebreaks first and remove them after the removal of the selectors.
You also can simplify the regexes a bit. Use
x(?=a|b)
instead ofx(?=a)|x(?=b)
. You also don't need the lazy match[^\}]*?
.Below is a working example. For clarity I only removed the
body
selector.You could further compress the stylesheet by removing spaces in front of
{
or after:
and,