I'm working with CSS values in my js/jquery application and to make values like "20px" or "100%" or "4.58 em" editable, they need to be separated into value / unit pairs. My regex is patchy and so far I have come up with this after hours of tinkering.
split_unit : function (v) {
if (typeof v === 'string' && v !== ""){
var split = v.match(/^(\d+(?:\.\d+)?)(.*)$/);
return {'value':split[1].trim(), 'unit':split[2].trim()};
}
else{
return { 'value':v, 'unit':"" }
}
}
"split_unit" is a method that splits a values like "20px", "100%", "4.58 em", "440" or "9.4" to object containing value and unit.
It works nicely with values like "20px", "100%", "4.58 em", "440" or "9.4",
however the regex does not appear to be working with negative values and values that start with a decimal point like so "-40px", ".40em", "-80", ".04" etc.
I can do a replace of the decimal point and the '-' minus/hyphen at the start of the function and then append it to the value string at the end, but there has to be a more elegant way of doing it.
How would I go about tweaking the regex or the function itself so it works with negative values and values starting with decimal points ?
Thank you for answering this and for your time.