Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Regular Expression to Parse CSS

I have CSS snippet like

.is-error{
  color: #d8000c;
}
.is-success{
  color: #4f8a10;
}

I want to parse it with regular expression in javascript such that i get an array, with class name and corresponding properties.

Regular Expression I wrote: /^(?:([\w.\-\>\~\_\s\^\'\"\=\#\*\[\]\:\,\+]+)\{(.*)\})$/

gives me output:

array[1] = .is-error
array[2] = color: #d8000c;}.is-success{color: #4f8a10

desired output:

array[1] = .is-error
array[2] = color: #d8000c;
array[3] = .is-success
array[4] = color: #d8000c;
like image 252
Junaid Hamza Avatar asked Dec 10 '25 00:12

Junaid Hamza


1 Answers

Don't try to match it with a complex regex. But, instead split using a less complex one.

For splitting, we can use String.split and pass the regex /[{}/ into it and then we use Array.map to trim the strings so as to get only the content and removing the white space. But prior to doing that, we will just remove the unwanted empty strings using Array.filter

var arr = str.split(/[{}]/).filter(String).map(function(str){
    return str.trim(); 
});

It also has the advantage of working on all css-rules and not just classes, provided the CSS is a valid one.

like image 155
Amit Joki Avatar answered Dec 12 '25 14:12

Amit Joki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!