自动检测数字替换非数字的正则表达式

时间:2022-09-19 09:34:05

直接给出代码了:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
 <HEAD>
 <TITLE> New Document </TITLE>
 <META NAME="Generator" CONTENT="EditPlus">
 <META NAME="Author" CONTENT="">
 <META NAME="Keywords" CONTENT="">
 <META NAME="Description" CONTENT="">
 </HEAD>
 <BODY>
 <input onkeyup='check(this)'/>
 </BODY>
 <script>
function check(obj){   
    var sreg = /^-+.*/g;
    var zero = /^0[1-9]+\.*\d*/g;
    var val = obj.value;
    var plus = '';
    if(sreg.test(val)){
        val = val.replace(/-+/g,'');       
        plus = '-';    
    }
    val = val.replace(/\s+/g,'');  
    if(/^\.+.*$/.test(val)){
        val = '';
    }
    val = val.replace(/[^\d\.]/,'');
    val = val.replace(/(^\d+\.{1})(\d*).*/g,'$1$2');
    val = val.replace(/(^\d+\.\d{3})\d*/g,'$1');
    val = val.replace(/^[0]*(0{1})([1-9]*)(.*)/g,'$1$2$3');    
    if(zero.test(val)){
        val = val.replace(/0([1-9]+)(.*)$/,'$1$2');
    }
    
    obj.value = plus+val;
}
 </script>
</HTML>

服务器之家写的一个替换 非数字与中英文逗号的函数,需要的朋友可以参考一下

?
1
2
3
4
5
function renumdou(str){
var regexp = /[^\d,,]]*/g;
newstr=str.replace(regexp,"");
return newstr
}