-1

Consider the following string:

var string="0px 0px 4.5px";

Now let's say I want to extract the numbers from that string. I will use the following regex:

var numbers=string.match(/\d+/g);

But what I get is:

["0","0","4"]

So you see that 4.5 was turned into an integer.So my question is how can I change the above regex to get floating numbers from a string

cssGEEK
  • 994
  • 2
  • 15
  • 38
  • 3
    regex? pfft... `"0px 0px 4.5px".split(" ").map(parseFloat)` – canon Mar 28 '16 at 22:35
  • @canon: Won't that spit out `["0px", "0px","4.5px"]`. Shouldn't it split on `px ` ? P.S: Checked it. It's works. –  Mar 28 '16 at 22:38
  • @noob That's what the `split()` returns, yes. But the call to `map()` then parses those values into floats. Try it in console. – canon Mar 28 '16 at 22:38
  • Hey stribnez, not ony is [dup](http://stackoverflow.com/questions/17374893/how-to-extract-floating-numbers-from-strings-in-javascript) the answer closed but the selected answer is _wrong_. –  Mar 28 '16 at 22:42

2 Answers2

0

Your answer is already in comment by canon.

But since you added the regex tag here is solution.

Regex: /(?:\d+(?:\.\d+)?|\.\d+)/g

Flags to use:

  • g for global search.

Explanation:

  • \d+ will match the integer part.

  • (?:\.\d+)? will match the decimal part which is optional.

  • \.\d+ for numbers with only decimal part.

Regex101 Demo

0

This is a good one (?:\d+(?:\.\d*)?|\.\d+)

Explained

 (?:
      \d+                 # Digits
      (?: \. \d* )?       # Optional dot (digits optional)
   |                    # or,
      \. \d+              # Dot digits
 )