views:

35

answers:

1

Possible Duplicate:
Format numbers in javascript

I have a string represents a number: "3507654" I need to split it on a parts, by 3, e.g "3 507 654"

Number can be any value, but always a number.

+6  A: 

You could do the following:

"3507654".replace(/(\d)(?=(?:\d{3})+$)/g, "$1 ")

But this is not very efficient since it’s O(n2).

Gumbo
nice answer. regex FTW.
hvgotcodes
… and there's a leading space if the number has 3n digits.
KennyTM
Real nice answer. Definitely +1
Kangkan
@KennyTM: Fixed that.
Gumbo
@Kenny: I was just about to mention how to fix that, but Gumbo updated his answer to include the fix already. +1.
Andy E
thanks, very elegants and hackers :) +1
Alex Ivasyuv