javascript - 输入只允许一个小数点

标签 javascript regex

我正在尝试在输入时格式化数字,您只能在其中插入有效数字。除了小数点外,我一切正常。输入框允许我插入任意数量的小数,但我只想允许一个(参见最后的 replace())。

element.oninput = e => {
    let value = e.currentTarget.value;
    let result = value
        // Remove anything that isn't valid in a number
        .replace(/[^0-9-.]/g, '')
        // Remove all dashes unless it is the first character
        .replace(/(?!^)-/g, '')
        // Remove all periods unless it is the last one
        .replace(/(?!)\./g, '');
    element.value = result;
}

https://jsfiddle.net/c4f1L3kv/1/

以下是一些有效的输入:

123.123
-123.12
123
-123
.123
-.123

以下是一些无效的输入:

123-123
1-2-3
123.123.123
123-123..12

最佳答案

如果您只想匹配后跟另一个句点字符的句点字符,那么您可以使用 positive lookahead就像下面的表达式:

/\.(?=.*\.)/g

解释:

  • \. - 匹配文字 . 字符
  • (?= - 正面前瞻的开始
    • .*\. - 匹配零个或多个字符,直到文字 . 字符。
  • ) - 正前瞻结束

var element = document.querySelector('input');
element.addEventListener('input', (event) => {
  event.target.value = event.target.value
    // Remove anything that isn't valid in a number
    .replace(/[^\d-.]/g, '')
    // Remove all dashes unless it is the first character
    .replace(/(?!^)-/g, '')
    // Remove all periods unless it is the last one
    .replace(/\.(?=.*\.)/g, '');
});
<input type="text" />


根据您的以下评论:

如果你想阻止用户在句点字符已经存在的情况下在字符串末尾添加句点字符,那么你可以使用表达式 /(\..*)\.$/ 并将第一个捕获组替换为自身,这将有效地删除捕获组中不存在的任何内容(即最后一个句点字符)。

var element = document.querySelector('input');
element.addEventListener('input', (event) => {
  event.target.value = event.target.value
    // Remove anything that isn't valid in a number
    .replace(/[^\d-.]/g, '')
    // Remove all dashes unless it is the first character
    .replace(/(?!^)-/g, '')
    // Remove the last period if there is already one
    .replace(/(\..*)\.$/, '$1')
    // Remove all periods unless it is the last one
    .replace(/\.(?=.*\.)/g, '');
});
<input type="text" />

关于javascript - 输入只允许一个小数点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42043695/

相关文章:

javascript - 有没有办法通过定时器运行javascript函数?

regex - 正则表达式如何在幕后工作(在 CPU 级别)?

php - Javascript 正则表达式并获取所有匹配项,它类似于 preg_match_all(PHP)

python - 在 Python 中使用正则表达式查找和替换文件中的单词列表

javascript - Aurelia 中 fetch() 的错误处理

javascript - 在事件回调中调用函数

javascript - 更改后如何设置下拉列表的默认值?

javascript - 为什么我的球消失了?

python - 2 个不同的文本 block 合并在一起。如果我知道 1 是什么,我可以将它们分开吗?

c# - 如何忽略C#中的正则表达式匹配?