Junaid Hamza
Junaid Hamza

Reputation: 41

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;

Upvotes: 3

Views: 1714

Answers (1)

Amit Joki
Amit Joki

Reputation: 59232

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.

Upvotes: 4

Related Questions