> var n = "12345678.91";
> n.split('').reverse().join('').match(/.{1,3}/g).join(' ').split('').reverse().join('').replace(/\s\.|,\./g, '.'));
> "12 345 678.91"
> n.match(/.{1,3}/g).join(' ');
> "123 456 78. 91"
The problem here is that RegExp is staring from left to right and produced wrong (from the task’s point of view) result. There is a two spaces where there shouldn’t be: after the dot and in the last triad (having two digits instead of three). First space I’ve eliminated adding regexp
replace function.
> n.match(/.{1,3}/g).join(' ').replace(/\.\s/g, '.');
> "123 456 78.91"
Now it seems OK on the right of the dot. But last triad has still two digits. This is because RegExp rules passed to the match function are applied from left to right. So until dot is found it is impossible to predict how triad will be formed. Instead of applying more complicated regexp I’ve decided to reverse numbers before to add group separator.
> n.split('').reverse().join('').match(/.{1,3}/g).join(' ');
> "19. 876 543 21"
This way I’ve passed over the problem with the direction rules have been applied to the input. As the result is reversed at this point, I’ve to switch it back to original order adding same functions, this time on the right end.
> n.split('').reverse().join('').match(/.{1,3}/g).join(' ').split('').reverse().join('');
> "12 345 678 .91"
This is pretty close to desired result nevertheless there is one surplus delimiter before the dot. It might be easily eliminated using replace function.
> n.split('').reverse().join('').match(/.{1,3}/g).join(' ').split('').reverse().join('').replace(/\s\./g, '.');
> "12 345 678.91"
That’s it.
Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.
Comments (2)
Commented:
Author
Commented:Open in new window