我试图使用JavaScript美化CSS代码。
缩小的CSS代码如下所示:
str = 'body{margin:0;padding:0;}section,article,.class{font-size:2em;}'
到目前为止,我可以通过使用多个替换来美化代码:
str.replace(/{/g, " {\n")
.replace(/}/g, "}\n")
.replace(/;/g,";\n")
.replace(/,/g, ",\n")这是可行的,但我想改进它。
发布于 2012-11-21 21:08:12
我认为很难减少正则表达式的数量,因为有时只需要换行,有时也需要制表符。有时你需要写回一个字符,有时两个字符。但是,下面列出的替换列表使CSS看起来相当不错:
str.replace(/\{/g, " {\n\t") // Line-break and tab after opening {
.replace(/;([^}])/g, ";\n\t$1") // Line-break and tab after every ; except
// for the last one
.replace(/;\}/g, ";\n}\n\n") // Line-break only after the last ; then two
// line-breaks after the }
.replace(/([^\n])\}/g, "$1;\n}") // Line-break before and two after } that
// have not been affected yet
.replace(/,/g, ",\n") // line break after comma
.trim() // remove leading and trailing whitespace使之成为:
str = 'body{margin:0;padding:0}section,article,.class{font-size:2em;}'看上去像这样:
body {
margin:0;
padding:0;
}
section,
article,
.class {
font-size:2em;
}如果您不关心这些省略的分号是否被放回原处,则可以通过更改顺序将其缩短一些:
str.replace(/\{/g, " {\n\t")
.replace(/\}/g, "\n}\n\n") // 1 \n before and 2 \n after each }
.replace(/;(?!\n)/g, ";\n\t") // \n\t after each ; that was not affected
.replace(/,/g, ",\n")
.trim()发布于 2012-11-21 20:52:56
我不知道CSS是否是一种常规语言(我的猜测是肯定的),但是无论怎样,这都应该可以用regex实现。
不需要匹配最后一个属性,不管它是否包含分号。第一次匹配所有关闭的大括号,就像您所做的一样,除了在每个大括号之前和之后添加一个换行符:
.replace(/}/g, "\n}\n")
然后匹配所有分号,但除外,在换行符之前(由上面的正则表达式插入),并在每个分号后面添加一个新行和选项卡,使用\t字符:
.replace(/;([^\n])/g, ";\n\t$1")
不幸的是,这只是冰山一角。如果您计划在这些选择器周围添加空格,请不要忘记查找所有不同类型的选择器,例如那些包含:或>的选择器。也许还有很多其他的事情你也需要考虑。
https://stackoverflow.com/questions/13501565
复制相似问题