Adding to Bryan's answer. And adding a note
- javascript support:
there was an error with the (?2)
- multiple classes:
.class, .class2 {...}
- class delimeters:
.class-name, .class_name
- empty class:
.class {}
- percentages:
width: 100%;
- quoted urls:
background: url("/img.jpg");
const multi = /((?:^\s*)([\w#.@*,:\-.:>,*\s]+)\s*{(?:[\s]*)((?:[A-Za-z\- \s]+[:]\s*['"0-9\w .,\/()\-!%]+;?)*)*\s*}(?:\s*))/mi
const example = `
div.css-class-10_9::hover, .active {
width: 100%;
background: rgba(1.0,0,1,1);
background-url: url("http://img.jpg");
}
div.css-class-10_9::hover,
.active {
width: 100%;
background: rgba(1.0,0,1,1);
background-url: url("http://img.jpg");
}
html {
background: white;
}
`
let out = example.replace(multi, '')
// "
// div.css-class-... {...}
// html {...}
// "
out = out.replace(multi, '')
// "html {...}"
out = out.replace(multi, '')
// ""
You can also add global to replace all at once
const global_re = /((?:^\s*)([\w#.@*,:\-.:>,*\s]+)\s*{(?:[\s]*)((?:[A-Za-z\- \s]+[:]\s*['"0-9\w .,\/()\-!%]+;?)*)*\s*}(?:\s*))/gmi
example.replace(global_re, '');
// ""
example.replace(global_re,'$1') // group 1 all css
//
// div.css-class-...{
// width...
// rest_css...
// }
//
// ...
//
// html {
// ...
// }
Class Names
example.replace(global_re,'$2\n\n') // group 1 all class names
// "
// div.css-class-10_9::hover, .active
//
// div.css-class-10_9::hover,
// .active
//
// html
// "
Class bodies (replace everything but class bodies)
example.replace(global_re,'$3\n')
// "
// width: 100%;
// background: rgba(1.0,0,1,1);
// background-url: url("http://img.jpg");
//
//
// width: 100%;
// background: rgba(1.0,0,1,1);
// background-url: url("http://img.jpg");
//
//
// background: white;
//
// "
https://regex101.com/r/fK9mY3/55
(Disclaimer: this definitely doesn't validate css)
ex: '............a {}' comes out true
.test{ fail:red;}valid ?