I need to use JavaScript split but I’m useless at regex so what i wanna do is take a text which is CSS like structure eg:
var str = "selector {
width: 100px;
height: 20px;
}
.anything{
margin: 5%;
}";
str.split(/regex goes here/);
Expected output
[
0 = selector{width: 100px; height: 20px;},
1 = .anything{margin: 5%;}
]
Hopefully it’s not too confusing but please ask if in doubt.
Thanks.
I wouldn’t use a split for this. Instead, use this regex to extract each rule:
Very simple, but should work as long as there aren’t { and } characters in the rules themselves (which I would expect would be rare). My regex ignores whitespace and newlines as long as the CSS is syntactically valid. I used
[\s\S]in place of.because.doesn’t match newlines.In your case, to extract the rules it would be:
EDIT:
As per the askers request, I have modified my regex to ignore a selector such as:
a {}. However, it will still catcha { }. I will try to find a solution for this but in the mean time you might just have to process each rule and remove empty ones.