Created
June 25, 2011 05:15
-
-
Save jhartikainen/1046179 to your computer and use it in GitHub Desktop.
Format a numeric string every three numbers
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
//Is this abuse of array functions? :D | |
'20000001'.split('').reverse().join('').match(/\d{3}|\d+$/g).map(function(s){ return s.split('').reverse().join(''); }).reverse().join(' '); | |
//produces "20 000 001" |
As cool as it looks, that's pretty wasteful :) How about this:
function (d, r) { while (d.length) { r.unshift(d.substr(-3, 3)); d = d.slice(0, -3); } return r.join(' '); } ('20000001', []);
It's 2-4 times faster depending on browser, it works in IE, plus, it's shorter! ;)
Yep that might be a bit more practical :)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The regex was missing a +