首页 > 解决方案 > 如何在此输入中仅输入数字和减号

问题描述

<div class="kinput">
  <input type="text" placeholder="Enter value" maxlength="7" id="kinput" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');">
</div>

我找到了这个表达

oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');"

但它不允许我输入减号。如果有办法我可以包含减号而不允许其他非数字字符..

标签: javascripthtml

解决方案


您可以将 包含-在正则表达式 ( [^0-9.-]) 中以忽略匹配中的该字符,并在替换中跳过该字符。

<div class="kinput">
  <input type="text" placeholder="Enter value" maxlength="7" id="kinput" oninput="this.value = this.value.replace(/[^0-9.-]/g, '').replace(/(\..*)\./g, '$1');">
</div>


推荐阅读