tomsseisums
tomsseisums

Reputation: 13357

regular expression to match CSS "<property>: <value>"

I've retrieved a CSS rule from document.styleSheets and am looking now to extract it's properties and values.

cssText = ".expl { position: absolute; background-color: rgb(204, 204, 204); max-width: 150px; }";

Is it possible with regular expressions to retrieve the properties and their appropriate values within a match? Plus, strip the trailing semi-colon.

I want to get the result as follows:

position: absolute // match 1
background-color: rgb(204, 204, 204) // match 2
max-width: 150px // match 3

I've only got to the point where I'm extracting what's within the brackets: (?<={)(.*)(?=}), have no clue with what should I continue.

How do I achieve this?

Thanks in advance!

Upvotes: 3

Views: 7313

Answers (4)

Cfreak
Cfreak

Reputation: 19309

Pull everything out between the brackets and then just split it out:

matches = cssrule.match(/{([^}]+)}/);
rules = matches[1].split(';');

Upvotes: 3

David Hellsing
David Hellsing

Reputation: 108472

My regexp is a bit rusty, but something like:

var arr = cssText.replace(/\s/g,'')
                 .replace(/^.*{([^}]+)}.*/,'$1')
                 .match(/([^;]+)/g);

should create:

["position:absolute","background-color:rgb(204,204,204)","max-width:150px"]

Upvotes: 2

Joseph Marikle
Joseph Marikle

Reputation: 78520

You could just split the string on the ;

document.getElementById(id).style.cssText.split(";")

EDIT:

note that the cssText property of a style object does not contain the selector

enter image description here

EDIT 2:

Ok I did a little more digging and it appears you are getting your cssText property from a CSSStyleRule object. This includes the selectors. You can get a semicolon delimited list of the actual rules with a little more tree traversal. You can get the style object with

document.styleSheets[1].cssRules[0].style.cssText;

instead of

document.styleSheets[1].cssRules[0].cssText;

See this drill down:

enter image description here

Upvotes: 4

CaffGeek
CaffGeek

Reputation: 22054

This breaks it all out into named items

\s*(?<rule>(?<selector>[^{}]+){(?<style>[^{};]+:[^{};]+;\s*)+})

If your parser doesn't support named groups (which javascript doesn't) remove the ?<text> from the regex, like this

\s*(([^{}]+){([^{};]+:[^{};]+;\s*)+})

Since your cssText may not contain the css selector, you may want to just split on ;. If it doesn't this works pretty good for parsing stylesheets. I used it in a tool I wrote to inline stylesheets.

Upvotes: 0

Related Questions