I'm rubbish at Regular Expressions, really!
What I'd like is to split a string containing a CSS property value into an array of [string,value,unit].
For example: if I supplied the .split() method with 1px it'd return ["1px",1,"px"]. If I were to supply, similarly, 10% it'd return ["10%",10,"%"].
Can this be done?
I appreciate all your help!
Update: I'd also like it to return ["1.5em",1.5,"em"] if 1.5em were supplied. But, if possible, still return null if supplied yellow. Unfortunately /^([0-9]*\.?[0-9]*)(.*)/ supplied with yellow would return y,,y!
Thanks so far guys!
"1px".match(/(\d*\.?\d*)(.*)/)
yields
["1px", "1", "px"]
I've updated the expression to match real numbers with leading and trailing decimals.
var expr = /(\d*\.?\d*)(.*)/,
cases = [
"1px",
"1.px",
"11.px",
"11.1px",
"11.11px",
"1.11px",
".11px",
".1px",
".px" // Invalid numeric value, but still preserves unit and can be handled as seen below
];
for ( var i=0,l=cases.length; i<l; ++i ) {
var r = cases[i].match(expr );
console.log(r, parseFloat(r[1], 10) || 0);
}
Results
["1px", "1", "px"] 1
["1.px", "1.", "px"] 1
["11.px", "11.", "px"] 11
["11.1px", "11.1", "px"] 11.1
["11.11px", "11.11", "px"] 11.11
["1.11px", "1.11", "px"] 1.11
[".11px", ".11", "px"] 0.11
[".1px", ".1", "px"] 0.1
[".px", ".", "px"] 0
Using capturing groups:
var matches = "100%".match(/^(\d+(?:\.\d+)?)(.*)$/);
You're in luck. match returns an array with the full match on the first position, followed by each group.split is probably wrong here, since you want to keep the full match. If you wanted to get ['100', '%'], for example, you could have done .split(/\b/).
Updated to enable fractions. Also, the use of both anchors will not match when the format isn't [number][unit], so null is returned.
Try:
cssProperty.match(/^([0-9]+\.?[0-9]*)(.*)/);
More complicated but will return parsed number and null for some garbage strings
String.prototype.unitSplit = function(parse){
var retArr = this.toString().match(/^([\d]*\.?[\d]+)([^\d]*)$/);
if(retArr && parse != undefined)
{
retArr[1] = (retArr[1].indexOf('.') >= 0)?parseFloat(retArr[1]):parseInt(retArr[1]);
}
return retArr;
}
/* Test cases */
"10px".unitSplit(); //["10px", "10", "px"]
"20%".unitSplit(true); //["20%", 20, "%"]
".8em".unitSplit(true); //[".8em", 0.8, "em"]
"127.0.0.1localhost".unitSplit(true); //null
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With