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