-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

4
  • 3
    regex? pfft... "0px 0px 4.5px".split(" ").map(parseFloat) Commented Mar 28, 2016 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. Commented Mar 28, 2016 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. Commented Mar 28, 2016 at 22:38
  • Hey stribnez, not ony is dup the answer closed but the selected answer is wrong. Commented Mar 28, 2016 at 22:42

2 Answers 2

0

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

Explained

 (?:
      \d+                 # Digits
      (?: \. \d* )?       # Optional dot (digits optional)
   |                    # or,
      \. \d+              # Dot digits
 )
Sign up to request clarification or add additional context in comments.

3 Comments

Oh yea ! to allow only decimal part too. Nice catch.
Yes that would be a good idea if it were true, as I thought it was until mere moments ago, that valid CSS can include something like 5.px.
Well then the 5. is matched.
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

5 Comments

It was and it's also wrong :)
@Pointy: * will allow many decimal parts.
well my supposition that 4.px is valid CSS doesn't seem to be true (though 4. + 4 is perfectly good JavaScript).
This will allow me to only get the first value which is "0" not all the values
@cssGEEK: Use global flag. Updated my answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.