Skip to content

Instantly share code, notes, and snippets.

@AlexKratky
Last active February 21, 2021 09:36
Show Gist options
  • Save AlexKratky/6e6523ef7f8182376239fe7c24742101 to your computer and use it in GitHub Desktop.
Save AlexKratky/6e6523ef7f8182376239fe7c24742101 to your computer and use it in GitHub Desktop.
Format number with spaces in text using regex
let str = 'This string contains two numbers. One is 50000 and the second one is 10000.';
// Edit (\s|\.) if the character after the number is not whitespace or dot
// Edit '$& ' if you want to insert different character from whitespace, for example to format number using ',' replace whitespace with '$&,'
console.log(str.replace(/\d(?=(\d{3})+(\s|\.))/g, '$& '));
// or
console.log(str.replace(/\B(?=(\d{3})+(?!\d))/g, " "));
// Output: This string contains two numbers. One is 50 000 and the second one is 10 000.
// suports also only number
function formatNumber(exp) { return exp.toString().replace(/\B(?=(\d{3})+(?!\d))/g, " "); }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment