Analysis of css measures

When I write a jQuery plugin, I like to specify CSS style distance options. I wrote a function that returns CSS String as values ​​in an object.

5px 10px returns top: 5px, right: 10px, bottom: 5px, left: 10px

Now I often use return values ​​to perform some calculations, and it’s not very nice to retrieve a measurement unit every time ...

I suck written regular expressions, can someone help me fulfill this function:

this.cssMeasure = function(cssString, separateUnits){ if ( cssString ){ var values = {} }else{ return errorMsg } var spacing = cssString.split(' ') var errorMsg = 'please format your css values correctly dude' if( spacing[4] ) { return errorMsg } else if ( spacing[3] ) { values = {top: spacing[0], right:spacing[1], bottom:spacing[2], left:spacing[3]} } else if ( spacing[2] ) { values = {top: spacing[0], right:spacing[1], bottom:spacing[2], left:spacing[1]} } else if ( spacing[1] ) { values = {top: spacing[0], right:spacing[1], bottom:spacing[0], left:spacing[1]} } else { values = {top: spacing[0], right:spacing[0], bottom:spacing[0], left:spacing[0]} } if (separateUnits) { $.each(values, function(i, value){ /* at this place i need to extract the measuring unit of each value and return them separately something like top: {value: 10, unit: 'px'}, right: {bla} and so on */ }) } return values } 

If you have an idea how to improve this feature, I am open to your comments.

+4
source share
2 answers

According to http://www.w3.org/TR/css3-values/#ltnumbergt , "A number can be an integer, or it can be zero or more digits, followed by a period (.), Followed by one or more digits ", in regexp

 \d+|\d*\.\d+ 

Add an optional character to it and make the group "non-exciting" to simplify parsing

 ([+-]?(?:\d+|\d*\.\d+)) 

Enumerating all possible units is tedious, so let the unit be any sequence of lowercase letters (including not a single one) or a percent sign

 ([az]*|%) 

Putting it all together

 propRe = /^([+-]?(?:\d+|\d*\.\d+))([az]*|%)$/ 

When applying this value to a value

  parts = "+12.34em".match(propRe) 

the numerical value will be indicated in parts [1], and the unit in parts [2]

+4
source
 switch (spacing.length) { case 1: values = {top: spacing[0], right:spacing[0], bottom:spacing[0], left:spacing[0]}; break; case 2: values = {top: spacing[0], right:spacing[1], bottom:spacing[0], left:spacing[1]}; break; case 3: values = {top: spacing[0], right:spacing[1], bottom:spacing[2], left:spacing[1]}; break; case 4: values = {top: spacing[0], right:spacing[1], bottom:spacing[2], left:spacing[3]}; break; default: return errorMsg; } if (separateUnits) { values = $.map(values, function(i, value){ matches = value.match(/([-+]?[\d.]*)(.*)/); return {value: matches[1]+0, unit: matches[2] ? matches[2] : 'px'}; }) } 
+2
source

Source: https://habr.com/ru/post/1307396/


All Articles