input框 金额正则表达式怎么写
时间: 2023-07-05 22:24:08 浏览: 68
可以通过监听 input 框的 `input` 事件,然后在事件处理函数中使用正则表达式来实现金额的格式化。
以下是一个简单的示例代码,可以实现在 input 框中输入金额时,自动格式化为两位小数的金额格式(如:1.00):
```html
<input type="text" id="money-input">
<script>
const moneyInput = document.getElementById('money-input');
moneyInput.addEventListener('input', function() {
// 获取输入框中的文本内容
const inputText = moneyInput.value;
// 替换非数字和小数点以外的字符
const formattedText = inputText.replace(/[^\d.]/g, '');
// 根据小数点将文本分割成整数部分和小数部分
const parts = formattedText.split('.');
let integerPart = parts[0];
let decimalPart = parts[1] || '';
// 限制小数部分最多只能有两位
decimalPart = decimalPart.slice(0, 2);
// 拼接整数部分和小数部分
const formattedMoney = `${integerPart}.${decimalPart}`;
// 更新输入框中的文本内容
moneyInput.value = formattedMoney;
});
</script>
```
需要注意的是,这个正则表达式只是一个简单的示例,可能无法满足所有的金额格式要求。如果需要更精确的匹配,建议使用第三方库,比如 Numeral.js 或 accounting.js。