javascript
44 lines · 8 steps
Live thousand separators without losing the caret
An input handler reformats numbers with locale separators while keeping the cursor anchored to the same digit.
Explained by
highlit
1function attachThousandSeparators(input, { locale = 'en-US' } = {}) {
2 const formatter = new Intl.NumberFormat(locale);
3 const groupSep = formatter.format(11111).replace(/\d/g, '')[0] || ',';
4 const decimalSep = formatter.format(1.1).replace(/\d/g, '')[0] || '.';
5
6 const countDigitsBeforeCaret = (value, caret) =>
7 value.slice(0, caret).replace(/[^\d]/g, '').length;
8
9 const caretForDigitCount = (value, digitsWanted) => {
10 if (digitsWanted === 0) return 0;
11 let seen = 0;
12 for (let i = 0; i < value.length; i++) {
13 if (/\d/.test(value[i])) {
14 seen++;
15 if (seen === digitsWanted) return i + 1;
16 }
17 }
18 return value.length;
19 };
20
21 const format = () => {
22 const raw = input.value;
23 const digitsBeforeCaret = countDigitsBeforeCaret(raw, input.selectionStart);
24
25 let [intPart, ...rest] = raw.split(decimalSep);
26 const negative = /^-/.test(intPart);
27 intPart = intPart.replace(/[^\d]/g, '');
28
29 let formatted = intPart
30 ? formatter.format(BigInt(intPart))
31 : '';
32 if (negative && formatted) formatted = '-' + formatted;
33 if (rest.length) formatted += decimalSep + rest.join('').replace(/[^\d]/g, '');
34
35 input.value = formatted;
36 const caret = caretForDigitCount(formatted, digitsBeforeCaret);
37 input.setSelectionRange(caret, caret);
38 };
39
40 input.addEventListener('input', format);
41 format();
42
43 return () => input.removeEventListener('input', format);
44}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Counting digits before the caret is a locale-agnostic anchor that survives reformatting when raw character positions don't.
- 2Intl.NumberFormat can be probed with sample values to discover the actual group and decimal separators for any locale.
- 3Returning a cleanup function makes an attach-style helper self-contained and easy to tear down.
Related explainers
javascript
const ROLE_PERMISSIONS = { admin: ['users:read', 'users:write', 'billing:read', 'billing:write'], manager: ['users:read', 'billing:read'], member: ['users:read'],
Role-based permissions middleware in Express
authorization
middleware
rbac
Intermediate
9 steps
javascript
import { useReducer, useEffect } from "react"; const initialState = { status: "idle", data: null, error: null };
Building a data-fetching hook in React
custom-hooks
usereducer
data-fetching
Intermediate
9 steps
javascript
const express = require('express'); const app = express(); app.get('/health', (req, res) => res.json({ status: 'ok' }));
Graceful shutdown in an Express server
graceful-shutdown
signal-handling
connection-tracking
Advanced
9 steps
javascript
import { useState, useEffect, useCallback } from 'react'; function getColumnCount(width) { if (width < 640) return 1;
A responsive column hook in React
custom-hooks
debouncing
responsive-design
Intermediate
7 steps
javascript
function initCharacterCounter(textarea, options = {}) { const maxLength = options.maxLength ?? 280; const warnThreshold = options.warnThreshold ?? 0.9;
A live character counter for textareas
dom
closures
accessibility
Intermediate
7 steps
javascript
function autoResizeTextarea(textarea, { maxHeight = Infinity } = {}) { const resize = () => { textarea.style.height = 'auto'; const contentHeight = textarea.scrollHeight;
Auto-resizing a textarea to fit its content
dom
event-listener
cleanup
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/live-thousand-separators-without-losing-the-caret-explained-javascript-25f9/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.