javascript - 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 ..
谢谢
解决方案
您可以使用
$('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')
- 保留除.
和第一个以外的任意数量的文本.
,并删除字符串中的所有其他点
推荐阅读
- angular - Ionic 3, angular 5 - webapp 的缓存问题
- javascript - 如何关闭 SignalR 中的客户端 JavaScript“集线器”连接?
- javascript - 尝试进行更清晰的异步 JSON 翻译调用
- javascript - 开玩笑的反应 onSubmit 不包括方法
- java - Java - 在导航到具有相同 html 模板的不同页面时断言类包含文本
- php - 使用 vsmoraes/laravel-pdf 包在 laravel 中返回带有变量的视图
- latex - 未定义的控制序列 \chapter
- sql - 在 SELECT 语句中声明和使用变量
- javascript - JavaScript强制点击下载?
- angular6 - 通过 Angular 应用程序代理 api 服务器