Last active
February 21, 2021 09:36
-
-
Save AlexKratky/6e6523ef7f8182376239fe7c24742101 to your computer and use it in GitHub Desktop.
Format number with spaces in text using regex
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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