我认为减少正则表达式的数量很难,因为有时您只需要换行符,有时您也需要一个制表符。有时您需要写回一个字符,有时是两个字符。但这里有一个使 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()