I think it's hard to reduce the number of regular expressions, since sometimes you need only a line break, sometimes you need a tab, too. Sometimes you need to write back one and sometimes two characters. But here is a list of replacements that makes the CSS look quite nice:
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
Makes this:
str = 'body{margin:0;padding:0}section,article,.class{font-size:2em;}'
Look like this:
body {
margin:0;
padding:0;
}
section,
article,
.class {
font-size:2em;
}
If you don't care about those omitted semicolons being put back in place, you can shorten this a bit though, by changing the order:
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()