Extend A Regular Expression To Negative Number
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, '')
Solution 1:
Uh, 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, "")
Solution 2:
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;
Solution 3:
Put your dash outside of the character class:
this.value = this.value.replace(/^-?[^0-9\.]/g, "");
Solution 4:
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]*/);
Solution 5:
It is only to put the negative symbol in front of the 0
this.value = this.value.replace(/[^-0-9\.]/g, "");
Post a Comment for "Extend A Regular Expression To Negative Number"