I have the following text as a JavaScript string
.mybox {
display: block;
width: 20px;
height: 20px;
background-color: rgb(204, 204, 204);
}
I want to convert to a JavaScript Object
var mybox = {
'display': 'block',
'width': '20px',
'height': '20px';
'background-color': 'rgb(204, 204, 204)';
};
Any ideas or already made scripts?
This is the beginning of a parser that may do what you want. Of course it needs work, especially if you want to handle any generic css that may be provided. This assumes that input css is written as you provided, with the first row being the name of the property, the last row being a ‘}’ and so on.
If you don’t want to handle only basic properties, writing a complex parser is not an easy task. For example, what if you declare something like:
This is valid css, but how would you extract a valid javascript variable name from it? How to convert
-webkit-transitioninto a meaningful property name? The whole task smells like you’re doing it all wrong. Instead of working on a parser, I’d work on a more stable solution at all.By the way, here is the code you may start from: