I want to extend the following regex to negative numbers.
this.value = this.value.replace(/[^0-9\.]/g, "");
I tried adding minus sign doing something like this, (/[^-0-9.]/g, "") but this allows minus sign to be entered anywhere in the number. I want to allow only one occurance of the minus sign at the beginning of the number. Later occurances of minus should be ignored.
Please help.
I want to extend the following regex to negative numbers.
this.value = this.value.replace(/[^0-9\.]/g, "");
I tried adding minus sign doing something like this, (/[^-0-9.]/g, "") but this allows minus sign to be entered anywhere in the number. I want to allow only one occurance of the minus sign at the beginning of the number. Later occurances of minus should be ignored.
Please help.
Share Improve this question asked Dec 12, 2012 at 17:45 user1528884user1528884 1211 gold badge4 silver badges14 bronze badges 05 Answers
Reset to default 11Uh, replacing every non-number character makes that a bit harder - it's like "negating" the regex. What I came up with is a negative lookahead, preventing a minus - which would be matched by [^0-9.]
- from beeing matched if it is in the beginning of the string (using a start anchor):
….replace(/(?!^-)[^0-9.]/g, "")
Why RegEx? How about:
var temp = parseFloat(this.value)
this.value = isNaN(temp) ? "" : temp;
This should also work:
var temp = +this.value;
this.value = isNaN(temp) ? "" : temp;
Put your dash outside of the character class:
this.value = this.value.replace(/^-?[^0-9\.]/g, "");
The regex in provided by you is faulty for the positive numbers itself as it will convert "100+200=300" to "100200300".
I suggest you try this: someString.match(/-?[\d]+.?[\d]*/);
It is only to put the negative symbol in front of the 0
this.value = this.value.replace(/[^-0-9\.]/g, "");