3

What's the best way to extract numbers (with dot in between sometimes)from string in one line?

var str = "ghjkhjgbkhj123.45khgbkhjgk67   8kjhgkj hg13.99sads";

I need an array of [123.45, 67, 8, 13.99];

str.match(/\d+/g) returns slightly different results - it doesn't count ".".

Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
Haradzieniec
  • 9,086
  • 31
  • 117
  • 212
  • http://stackoverflow.com/questions/12117024/decimal-number-regular-expression-where-digit-after-decimal-is-optional – rock321987 May 23 '16 at 15:15

2 Answers2

9

Use regex as /\d+(?:\.\d+)?/g

var str = "ghjkhjgbkhj123.45khgbkhjgk67   8kjhgkj hg13.99sads";

console.log(
  str.match(/\d+(?:\.\d+)?/g)
);

Regex explanation here.

Regular expression visualization

Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
2

str.match(/[.\d]+/g) will do what you are asking for. It will allow for more than one dot, so if you want to do something "sensible" given 123.456.789 you will probably want something more complicated -- but in that case you should first figure out exactly what more sensible thing you want.

Gareth McCaughan
  • 19,888
  • 1
  • 41
  • 62