-4

I need to parse CSS file for selectors and using Javascript to find all CSS/CSS3 selectors inside the file correctly.

For example:

.hello { ... declaration ... }
.world::after { ... declaration ... }
#id1, #id2 { ...declaration... }.top{ ..declaration.. }

I need to get an array of elements: [".hello", ".world::after", "#id1", "#id2", ".top"]

Thank you!

xercool
  • 883
  • 1
  • 8
  • 24
  • 6
    You can't just ask people on stack overflow to solve your problem without you doing any actual work to find a solution. Show us code you've tried. Show us research you've done. See [this](https://stackoverflow.com/help/how-to-ask). – Isaac Vidrine Oct 19 '18 at 19:57
  • 2
    Possible duplicate of [How do you read CSS rule values with JavaScript?](https://stackoverflow.com/questions/324486/how-do-you-read-css-rule-values-with-javascript) – ControlAltDel Oct 19 '18 at 19:57

1 Answers1

0

You can use the following regex to split your text, so you have an array of matches:

/\{.*?\}|,|\>|\s/g

The regex will find, what we don't want: First a '{', followed by zero or more of any character (non-greedy) OR acomma OR a '>' OR a White Space. It uses the Global falg to catch all.

Then you need to replace those matches with an empty string and you have an array of selectors.

Example:

var css = '.hello { ... declaration ... }\r\n'
    + '.world::after { ... declaration ... }'\r\n'
    + '#id1, #id2 { ...declaration... }.top{ ..declaration.. }';

var selectorArray = css.split(/\{.*?\}|,|\>|\s/g);

You will have to remove empty elements in the array.

Poul Bak
  • 10,450
  • 5
  • 32
  • 57