Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: replace everything but numbers and allow only one dot

This works for integers, e.g.:

'123x'.replace(/\D/g, '')
'123'

Which regular expression would achieve the same, but allowing only one dot? Examples:

  • 1 -> 1
  • 1x -> 1
  • 10. -> 10.
  • 10.0 -> 10.0
  • 10.01 -> 10.01
  • 10.01x -> 10.01
  • 10.01. -> 10.01
like image 290
Tiago Fernandez Avatar asked Oct 14 '25 07:10

Tiago Fernandez


1 Answers

With two replaces:

console.log("a12b3.1&23.0a2x".replace(/[^.\d]/g, '')
                             .replace(/^(\d*\.?)|(\d*)\.?/g, "$1$2"));

The first action will remove all characters other than digits and points

The second replacement matches sequences of digits possibly followed by a point, but it does so in two different ways. When such sequence occurs at the start of the string, the optional point is put inside the first capture group, while for all other matches, the point is outside the (second) capture group.

There are two capture groups, but for any given match, only one of them will actually have content. So the captured content can be reproduced in either case with $1$2. This will include the first point, but exclude any other.

like image 116
trincot Avatar answered Oct 18 '25 09:10

trincot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!