Mustapha GANGA
Mustapha GANGA

Reputation: 833

How to parse property/value pairs from a CSS text

How can I extract all property/value pairs present in a CSS text

Example : From this CSS

var cssText = "background-image:url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8\"); color:green; content:'(test)'";

I have to extract key/value pairs :

background-image =>  url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8")
color => green
content => "(test)"

I tried cssText.split(';'), but it doesn't work because the base64 code contains a ;

Upvotes: 3

Views: 1608

Answers (3)

Mustapha GANGA
Mustapha GANGA

Reputation: 833

In some cases we are not in the context of an html document, here a function based on Regex to extract css rules :

var parseCssRules = function (cssText) {
    var tokenizer = /\s*([a-z\-]+)\s*:\s*((?:[^;]*url\(.*?\)[^;]*|[^;]*)*)\s*(?:;|$)/gi,
    obj = {},
    token;
    while ( (token=tokenizer.exec(cssText)) ) {
       obj[token[1].toLowerCase()] = token[2];
    }
   return obj;
};

Upvotes: 0

nonopolarity
nonopolarity

Reputation: 151206

You can try this:

let element = document.createElement("div");

element.style = "background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8\"); color:green; content:'(test)'";

console.log([...element.style]);
for (name of element.style) console.log(name, ":", element.style[name]);

Output:

["background-image", "color", "content"]

background-image : url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8")
color : green
content : "(test)"

JSFiddle: https://jsfiddle.net/vb9q1sot/

Tested on the current Google Chrome, Firefox, and Safari. Testing on browser compatibility needed such as for MS Edge or Internet Explorer.

Upvotes: 4

Greggers
Greggers

Reputation: 161

If you have a space after each ; but not in the base64, then just add the space to the split argument.

cssText.split('; ')

Upvotes: 1

Related Questions