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.)