0

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

2 Answers 2

2

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).

Sign up to request clarification or add additional context in comments.

3 Comments

I was only linking to it as a list of CSS attributes, not as a learning resource.
It works... the only problem is that I only get the first rule.
You have to keep matching, not match just once. In python you'd use findall instead of find. I'm sure there's something similar in javascript.
2

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');​​​

1 Comment

This is great! it does exactly what I need.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.