Skip to content

Instantly share code, notes, and snippets.

@jhartikainen
Created June 25, 2011 05:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jhartikainen/1046179 to your computer and use it in GitHub Desktop.
Save jhartikainen/1046179 to your computer and use it in GitHub Desktop.
Format a numeric string every three numbers
//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"
@jhartikainen
Copy link
Author

The regex was missing a +

@danstocker
Copy link

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! ;)

@jhartikainen
Copy link
Author

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