0

I have a function which I am calling on the input event of a form input, to filter out any characters which don't belong in a floating point number:

return value.replace(/[^0-9\.]/g, '');

As it stands, though, it doesn't allow a minus sign. How do I adapt this so that it will only allow an optional initial minus sign and then the numbers (i.e., 0 to 9 and .)? I can't quite get my ahead round the negation of the pattern with regex.

LATER: Decided that the best thing to do was to treat any minus sign separately before considering the regex. This is what I settled on:

function ensureFloatingPoint(value){
  let val=value;
  if(val==='-') {
     return val;
  }
  let sign="";
  if(val.startsWith("-")){
    sign="-";
    val=val.substring(1);
  }
  val = val.replace(/[^0-9\.]/g, '');
  if(sign){
    val=sign+val;
  }
  return val;
}

It strikes me as over-verbose but it does the job.

(The question isn't really a duplicate as I'm asking about excluding characters, not accepting them.)

John Moore
  • 6,739
  • 14
  • 51
  • 67
  • `/[^0-9\.\-]/g`, I'd suggest using some online tools to help with creating regex, personally I use [RegExr](https://regexr.com/) but I know there are more to choose from – George Nov 13 '17 at 16:25
  • That allows the user to enter a minus sign, sure, but it doesn't stop them entering it in the middle of the number - I want to restrict it to the first character. – John Moore Nov 13 '17 at 16:28
  • This is the opposite. Matching things you do want instead. `^[\-\.\0-9]?[0-9\.]+$` https://regex101.com/r/2gm0fK/1/ The question tagged as the duplicate works much better. – ktilcu Nov 13 '17 at 16:30
  • OK, so given that I am currently replacing each undesirable character in the input with "", how do I change things around to allow instead of denying? I can imagine that I might return the value unchanged if it matches, but what do I return if it doesn't match? If I return "" then I wipe out all previously entered valid characters. – John Moore Nov 13 '17 at 17:37

0 Answers0