0

I like to output a formatted number with a space after every two numbers, I've tried this:

 function twoSpaceNumber(num) {
    return num.toString().replace(/\B(?<!\.\d)(?=([0-9]{2})+(?!\d))/g, " ");
}

twoSpaceNumber(12345678) => 1 23 45 67 89 ( should start with 12 ? )

and also when it starts with 0 I had very strange output

twoSpaceNumber(012345678) => 12 34 56 78

Dominik
  • 6,078
  • 8
  • 37
  • 61

3 Answers3

2

Pass num as a string, not a number, else the leading zeros will disappear and use

function twoSpaceNumber(num) {
  return num.replace(/\d{2}(?!$)/g, "$& ");
}

The regex matches two digits that are not at the end of string (in order not to add a space at the string end).

JavaScript demo

const regex = /\d{2}(?!$)/g;
function twoSpaceNumber(num) {
  return num.replace(regex, "$& ");
}
const strings = ['123456789','012345678'];
for (const string of strings) {
  console.log(string, '=>', twoSpaceNumber(string));
}
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
1

Please consider

var s = "1234456";
var t = s.match(/.{1,2}/g);
var u = t.join(" ");
console.log(u);

which logs

12 34 45 6

and

var s = "ABCDEF";
var t = s.match(/.{1,2}/g);
var u = t.join(" ");
console.log(u);

which logs

AB CD EF

Note that s is a string.

Is that what you need?

Andrew Morton
  • 24,203
  • 9
  • 60
  • 84
0

If you don't mind a non-regex approach:

function twoSpaceNumber(num) { 
    var res = '';
    num += '';
    for(var i = 0; i < num.length; i+=2)
    {    
        res += num.substr(i,2) + ' ';
    }
    return res.trim();
}
  • Do remember that if you want a 0 at the front of the number, you need to pass it as a string otherwise javascript will ignore it – Paulo Ricca Oct 14 '20 at 20:58