最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Extend a regular expression to negative number - Stack Overflow

programmeradmin1浏览0评论

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 0
Add a comment  | 

5 Answers 5

Reset to default 11

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, "")

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, "");
发布评论

评论列表(0)

  1. 暂无评论