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
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
javascript
import { useState, useEffect, useCallback, useRef } from 'react'; const cache = new Map(); const inflight = new Map();
Building a stale-while-revalidate hook in React
caching
request-deduplication
custom-hooks
Advanced
10 steps
javascript
import { useEffect, useRef, useState } from 'react'; export function useDelayedFlag(active, delay = 300) { const [visible, setVisible] = useState(false);
Delaying a loading spinner with a React hook
custom-hooks
debouncing
cleanup
Intermediate
8 steps
javascript
const SWIPE_THRESHOLD = 80; const MAX_TRANSLATE = 120; export function attachSwipeToDismiss(element, onDismiss) {
Building a swipe-to-dismiss gesture in JS
touch-events
gesture-detection
dom-manipulation
Intermediate
10 steps
javascript
const { pool } = require('./db'); function withTransaction() { return async (req, res, next) => {
A per-request transaction middleware in Express
middleware
database-transactions
connection-pooling
Advanced
7 steps
javascript
function collapseConsecutiveLogs(lines, { keyFn = (l) => l.message } = {}) { const groups = []; for (const line of lines) {
Collapsing consecutive log lines in JavaScript
grouping
run-length-encoding
data-transformation
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.