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
  • 43,180
  • 11
  • 50
  • 79
peter flanagan
  • 9,195
  • 26
  • 73
  • 127

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
  • 43,180
  • 11
  • 50
  • 79