user1596922
user1596922

Reputation: 11

How to add spaces to every two numbers with JavaScript?

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

Upvotes: 1

Views: 1304

Answers (3)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626689

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

Upvotes: 3

Andrew Morton
Andrew Morton

Reputation: 25013

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?

Upvotes: 1

Paulo Ricca
Paulo Ricca

Reputation: 36

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();
}

Upvotes: 0

Related Questions