Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get every value from a box-shadow by regex

I'm looking for suggestions for a problem I'm having right now. I want to be able to change programatically the values of a box-shadow ie: box-shadow: h-shadow v-shadow blur spread color inset;.

And my issue is worst, I need it to be at least 2 properties together.

Example output of chrome: box-shadow: rgb(0, 0, 0) 0px 5px 10px, rgb(255, 255, 255) 0px 4px 10px inset;

So my issue is

  1. how can I first separate the two styles, just .split(",") wont cut it because it creates an array because of rgb(,,)
  2. If I get to split it, how to take care in case of HEX, rgb, or rgba, would a regex suffice?

Edit: I have to be able to make this splits in the browser, that's why I'm looiking for a js solution

Thank you.


Solution

Using @BYossarian answer I've added the following to continue the split the different box-shadow values

string.split(/,(?![^(]*))/);

and the following to split the white spaces

string.split(/ (?![^(]*))/);

outputting

["rgb(0, 0, 0)", "0px", "5px", "12px", "0px"]

The rest is just finding strings

var box_shadow_properties = box_shadow.split(/ (?![^(]*))/);

ie: getting the h-shadow v-shadow blur spread properties if(box_shadow_properties[i].indexOf("px") !== -1)

ie: getting the color property if (box_shadow_properties[i].indexOf("rgb") !== -1 || box_shadow_properties[i].indexOf("#") !== -1)

Hope someone finds this helpful

like image 384
Francis Reynolds Avatar asked Nov 13 '13 00:11

Francis Reynolds


1 Answers

In terms of splitting the string, the only commas should either be within brackets as part of a colour value, or separating the various box-shadow values. Since you want to split along the latter, you need to look for commas which aren't followed by an unopened closing bracket. i.e. commas that aren't followed by a ')' without a '(' inbetween the comma and the ')'. You can do that using the regex:

/,(?![^\(]*\))/

So that you'd use:

string.split(/,(?![^(]*))/);

Then in terms of identifying the colour values, you might want to start by looking at:

http://www.w3.org/TR/css3-color/

like image 180
Ben Jackson Avatar answered Sep 29 '22 23:09

Ben Jackson