appcropolis
appcropolis

Reputation: 276

How can I use regular expression to extract CSS rules from a string

In Javascript, I have a CSS selectors and I would like to extract the rules:

var cssOriginalString = 'p:hover { color: red; font-weight: bold;}';
var cssFinalString = 'color: red; font-weight: bold;';

My goal is to group all the rules inside an array:

var rulesArray = ['color: red;', 'font-weight: bold;'];

Any idea?

-- appcropolis

Upvotes: 0

Views: 1173

Answers (2)

Explosion Pills
Explosion Pills

Reputation: 191749

Your question seems to be asking for a regular expression, but it is very general. I need to know a lot more about the input string (for example, can you have two rulesets on the same line? Can you have one ruleset on multiple lines? Is it possible or a concern for "}" to appear in a rule? What about @ queries?). A very simplistic expression for a single ruleset on a single line:

cssOriginalString.replace(/.*{([^}]+)}/, '$1');​​​

Upvotes: 2

mathematical.coffee
mathematical.coffee

Reputation: 56915

You could try using regex:

[a-z-]+ *:[^:;]+;

The [a-z-]+ matches the css attribute names. I'm pretty sure they're lower case letters and hyphens, based on W3schools CSS attributes reference. However you could modify this if you feel differently (allow capital letters, etc). The loosest possible regex I'd recommend would be [\w-]+, which allows letters, numbers, underscore, and hyphen.

The *: is the separating colon, spaces allowed around it.

The [^:;]+; is the attribute value followed by a semi-colon. I've said that the attribute value can't contain a colon : or semi-colon ; to prevent it from matching across multiple attributes. You could also try .*?; here (the ? is important to make the match non-greedy, so it doesn't match over multiple attributes).

Upvotes: 2

Related Questions