Skip to content

Instantly share code, notes, and snippets.

@stembrain
Created May 25, 2021 20:25
Show Gist options
  • Save stembrain/937331534fc9649aa020efa23728bcc9 to your computer and use it in GitHub Desktop.
Save stembrain/937331534fc9649aa020efa23728bcc9 to your computer and use it in GitHub Desktop.
format numbers on the page with commas
var ignoreNodes = new Set(['INPUT', 'TEXTAREA']);
function walk(node) {
if (ignoreNodes.has(node.tagName)) {
return;
}
switch (node.nodeType) {
// Element
case 1:
// Document
case 9:
// Document fragment
case 11: {
let next, child = node.firstChild;
while (child !== null) {
next = child.nextSibling;
walk(child);
child = next;
}
break;
}
// Text node
case 3: {
node.nodeValue = node.nodeValue.replace(/(^\d*\.?\d+$)+/g, function replacer(match) {
return new Intl.NumberFormat('en-US').format(match)
})
break;
}
}
}
walk(document.body)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment