.split("1px") into ["1px",1,"px"] in Javascript

javascript, regex, split

Solution

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.

Problem

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!

Original source