1

So I am having a string that is created via function and then another function gets that string and takes only the numbers out of it. The string always looks like this (only the numbers change):

"rgba(123,213,321,0.23)"

So I want to get an array from this string like this:

strArray[0] == 123
strArray[1] == 213
strArray[2] == 321
strArray[3] == 0.23

I want to get both round and decimal numbers in one array. I am using this:

strArray = str.match(/(\d+)/g);

But it doesn't do the job because the decimal number is rounded. This means that when I have the same string as above, I get:

strArray[0] == 123
strArray[1] == 213
strArray[2] == 321
strArray[3] == 0

I also have to point out that I am not quite experienced with regex (actually not experienced at all). I got this line of code from somewhere. So I would be thankful if you explain the regex part in your answer (if there is one).

Robert
  • 10,403
  • 14
  • 67
  • 117
dodov
  • 5,206
  • 3
  • 34
  • 65
  • `\d` matches to any number, and `+` matches to "one or more" so the last one would be messed up (`.` isn't a number right?). You could try (\d+ | 0\.\d+)? instead. – Joe May 05 '14 at 20:47
  • possible duplicate of [Decimal number regular expression](http://stackoverflow.com/questions/12117024/decimal-number-regular-expression) – Pedro Lobito May 05 '14 at 20:50
  • Why are you parsing CSS with RegEx anyway? – tenub May 05 '14 at 20:51

1 Answers1

1

You can use this regex:

strArray = str.match(/(\d+(?:\.\d+)?)/g);
//=> ["123", "213", "321", "0.23"]
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • 2
    Note that `.23` won't be matched even though it is valid and `123.01` would be matched even though it is invalid. – tenub May 05 '14 at 20:48