需要帮助jquery中的正则表达式。 这段代码只允许输入一个点和一个数字,但是有必要在开始时让减号通过(对于负值)
$(function(){
$('.number_dots').on('input', function(){
this.value = this.value.replace(/^\.|[^\d\.]|\.(?=.*\.)|^0+(?=\d)/g, '');
});
});
已解决 解决方案:
$(function(){
$('.number_dots').on('input', function(){
//this.value = this.value.replace(/^\.|[^\d\.]|\.(?=.*\.)|^0+(?=\d)/g, '');
var value = this.value;
value = value.trim();
//If minus symbol occur at the beginning
if(value.charAt(0) === '-'){
value = value.substring(1, value.length);
value = "-"+value.replace(/^\.|[^\d\.]|\.(?=.*\.)|^0+(?=\d)/g, '');
}else{
value = value.replace(/^\.|[^\d\.]|\.(?=.*\.)|^0+(?=\d)/g, '');
}
console.log(value);
this.value = value;
});
});
答案 0 :(得分:2)
此正则表达式(^-?[0-9]\d*(\.\d+)?$
)要匹配正确的+/-小数,并且要删除不正确的多余数字,请使用以下代码。
var val="-12XXX.0abc23";
val = val.replace(/^\.|[^-?\d\.]|\.(?=.*\.)|^0+(?=\d)/g, '');
console.log(val);
答案 1 :(得分:1)
您可以尝试以下代码
var value = '-423423.44';
value = value.trim();
//If minus symbol occur at the beginning
if(value.charAt(0) === '-'){
value = value.substring(1, value.length);
value = "-"+value.replace(/^\.|[^\d\.]|\.(?=.*\.)|^0+(?=\d)/g, '');
}else{
value = value.replace(/^\.|[^\d\.]|\.(?=.*\.)|^0+(?=\d)/g, '');
}
console.log(value);