C#(Xamarin)中使用正则表达式实现货币格式化
How to Auto-Add Commas to Currency Inputs While Typing Using Regex
Great question! Adding dynamic comma formatting to currency inputs makes them much more user-friendly. Here's a practical approach using JavaScript and regex that works seamlessly as the user types:
Step-by-Step Implementation
1. HTML Setup
First, create a text input (avoid type="number" since it doesn't support commas natively):
<input type="text" id="currencyInput" placeholder="$0" autocomplete="off">
2. JavaScript Logic
We'll listen for input events, sanitize the value, apply regex formatting, and maintain proper cursor position (critical for good UX):
const currencyInput = document.getElementById('currencyInput'); currencyInput.addEventListener('input', function(e) { // Capture current value and cursor position let currentValue = e.target.value; const originalCursorPos = e.target.selectionStart; // Sanitize input: keep only $ and digits, remove existing commas const sanitized = currentValue.replace(/[^$\d]/g, ''); // Split into currency symbol (if present) and numeric part const [currencySymbol, rawNumbers] = sanitized.startsWith('$') ? ['$', sanitized.slice(1).replace(/,/g, '')] : ['', sanitized.replace(/,/g, '')]; // Use regex to add commas every 3 digits from the right const formattedNumbers = rawNumbers.replace(/\B(?=(\d{3})+(?!\d))/g, ','); // Combine symbol and formatted number const newValue = currencySymbol + formattedNumbers; // Calculate new cursor position (adjust for added/removed commas) const commasBeforeCursorOld = (currentValue.slice(0, originalCursorPos).match(/,/g) || []).length; const commasBeforeCursorNew = (newValue.slice(0, originalCursorPos).match(/,/g) || []).length; const adjustedCursorPos = originalCursorPos + (commasBeforeCursorNew - commasBeforeCursorOld); // Update input value and restore cursor e.target.value = newValue; e.target.setSelectionRange(adjustedCursorPos, adjustedCursorPos); });
3. How the Regex Works
The key regex pattern here is /\B(?=(\d{3})+(?!\d))/g:
\B: Matches a non-word boundary (avoids adding a comma at the start of the number)(?=(\d{3})+(?!\d)): A positive lookahead that checks for one or more groups of 3 digits, with no additional digits after them. This ensures commas are inserted from right to left, exactly where needed.
Key Notes for Improvement
- Support Other Currencies: Modify the sanitization regex to include symbols like
€,£, or¥(e.g.,/[^$€£¥\d]/g) - Negative Values: Adjust the logic to handle leading
-signs by splitting the symbol, negative sign, and numbers separately - Framework Adaptation: For React/Vue, use state to manage the input value and apply the same formatting logic when updating state
- Paste Handling: The
inputevent automatically handles pasted content, so no extra code is needed for that
内容的提问来源于stack exchange,提问作者MainakChoudhury
相关产品推荐
相关产品推荐

