首页 > 解决方案 > jQuery - JavaScript 正则表达式只允许数字和减号作为第一个字符

问题描述

我希望用户只在我的输入中输入数值,因此我在下面输入了代码。

<input type="text" class="form-control rounded-pill bg-light" autocomplete="off" name="free_credit_amount" id="free_credit_amount" placeholder="Free credit amount">

$('body').on('keyup', '#free_credit_amount', function(){
    this.value = this.value.replace(/[^0-9\.]/g,'');
});

这对我来说很好..但是我有一个要求,用户也可以输入负值..类似的东西-500 ,因此我已经更新了我的 JavaScript 正则表达式,如下所示..

$('body').on('keyup', '#free_credit_amount', function(){   
   this.value = this.value.replace(/[^-0-9]/g,'');
});

这对我来说也很好用,因为我minus (-)可以输入符号并且可以输入类似的值500-500但是,我想稍微提供一下这个正则表达式。目前正在发生的事情,我也可以输入类似的值500-。这不应该被允许..我只希望我minus (-)只被添加为第一个字符..

我曾尝试使用其他各种正则表达式,例如this.value = this.value.replace(/(\+|\-)?[^-0-9]/g,''); this.value = this.value.replace(/^[-][a-zA-Z0-9.,$;]/g,'');

但是那些正则表达式都没有为我工作..

有人可以帮我实现这个plz ..

谢谢

标签: javascriptjqueryregex

解决方案


您可以使用

$('body').on('input', '#free_credit_amount', function(){
    var position = this.selectionStart;
    var oldval = this.value;
    var newval = this.value.replace(/[^0-9.-]/g, '').replace(/^(-)|-+/g,'$1').replace(/^([^.]*\.)|\.+/g, '$1');
    this.value = newval;
    if (oldval != newval) {
        this.selectionEnd = position-1;
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="form-control rounded-pill bg-light" autocomplete="off" name="free_credit_amount" id="free_credit_amount" placeholder="Free credit amount">

这里,

  • .replace(/[^0-9.-]/g, '')- 删除除数字、点和连字符以外的所有字符
  • .replace(/^(-)|-+/g,'$1')- 将连字符保留在字符串的开头并删除所有其他连字符
  • .replace(/^([^.]*\.)|\.+/g, '$1')- 保留除.和第一个以外的任意数量的文本.,并删除字符串中的所有其他点

推荐阅读