0

I am trying to write a regex that replaces anything that isn't a digit or a . in a string.

For example:

const string = 'I am a 1a.23.s12h31 dog'`
const result = string.replace(/[09.-]/g, '');
// result should be `1.23.1231`

Can anyone see what I am doing wrong here.

Jack Bashford
  • 40,575
  • 10
  • 44
  • 74
peter flanagan
  • 7,650
  • 21
  • 64
  • 112

1 Answers1

1

You could change your regex to [^0-9.]+:

const result = string.replace(/[^0-9.]+/g, "");

Alternatively, if you don't want a regex, use split and filter, then join:

const result = string.split("").filter(s => isNaN(s) || s == ".").join("");
Jack Bashford
  • 40,575
  • 10
  • 44
  • 74