我認爲很難減少正則表達式的數量,因爲有時你只需要一個換行符,有時候你也需要一個選項卡。有時你需要寫回一個,有時甚至兩個字符。但這裏是使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()
爲什麼不使用預先構建的css縮小器? http://stackoverflow.com/questions/787789/any-recommendations-for-a-css-minifier – tjameson
@tjameson他希望UN-minify,而不是縮小。 – ean5533
@tjameson他正在尋找一位美麗的人,而不是一個縮小者。 –