2

I have a number string, eg. 123456789

I want to split them four in a group, such that it would be 1 2345 6789.

I tried with

string.match(/.{1, 4}/g).join(' ');

but it only gives 1234 5678 9

I also tried to reverse it first,

string.split('').reverse().join('').match(/.{1,4}/g).join(' ')

but it gives 1 5432 9876 instead...

any hints?

Andreas
  • 21,535
  • 7
  • 47
  • 56
Derekyy
  • 1,018
  • 4
  • 18
  • 31
  • 1
    Possible duplicate of [How to print a number with commas as thousands separators in JavaScript](http://stackoverflow.com/questions/2901102/how-to-print-a-number-with-commas-as-thousands-separators-in-javascript) – Andreas Nov 09 '15 at 18:11
  • 2
    `string.match(/.{1,4}(?=(?:.{4})*$)/g)` should do but is quite ugly. Try a loop with `.slice` instead. – Bergi Nov 09 '15 at 18:11
  • @Bergi thanks so much, it works well! – Derekyy Nov 09 '15 at 18:15

3 Answers3

1

There's probably a better way to do it, but this seems to work:

string.split('').reverse().join('').match(/.{1,4}/g).join(' ').split('').reverse().join('')

https://jsfiddle.net/5w7a0gxc/

miken32
  • 42,008
  • 16
  • 111
  • 154
0

An alternate method using a for-loop:

var s = "123456789";
var n = 4;
for (var i = s.length - n; i > 0; i -= n)
    s = s.substr(0, i) + " " + s.substring(i);
// Now s == "1 2345 6789"
Nayuki
  • 17,911
  • 6
  • 53
  • 80
0

I do have another answer using while loop, after Beigi's comment:

var text = '123456789';
var result = '';
var split = text.split('');
var start = 0;
var end = text.length % 4;
while (end <= isLoading.length) {
  result += split.slice(start, end).join('') + ' ';
  start = end;
  end += 4;
}
Derekyy
  • 1,018
  • 4
  • 18
  • 31