3

With an input like 123456789, how can I convert it into a format like 123 456 789 with JavaScript?

split("").join(" "); returns 1 2 3 4 5 6 7 8 9.

Penny Liu
  • 15,447
  • 5
  • 79
  • 98
Christopher
  • 3,379
  • 7
  • 25
  • 36
  • not tested, but how about `.split(/(\d{3})/)`? – Marc B Aug 14 '15 at 14:46
  • 1
    You have to start by figuring out what the proper split is: "12 34 56 78 9" is just as valid as "123 456 789" or "1234 5678 9". Too broad. – duffymo Aug 14 '15 at 14:46
  • You can use substr `num.substr(0,3)+' '+num.substr(3,3)+' '+num.substr(6,3)` – suvroc Aug 14 '15 at 14:47
  • Possible duplicate of [How to print a number with commas as thousands separators in JavaScript](https://stackoverflow.com/questions/2901102/how-to-print-a-number-with-commas-as-thousands-separators-in-javascript) – shrpne May 14 '18 at 17:06

6 Answers6

11

If you always want the spaces to be by how far from the right you are, use a lookahead which counts in threes

'12345678'.replace(/(\d)(?=(\d{3})+$)/g, '$1 '); // "12 345 678"

(?=pattern) is the lookahead, \d{3} is 3 digits, and (pattern)+ means repeat the last pattern one or more times (greedily) until a the end of the String $

Paul S.
  • 64,864
  • 9
  • 122
  • 138
5

Use the substring method:

var num = "123456789";
var result = "";
var gap_size = 3; //Desired distance between spaces

while (num.length > 0) // Loop through string
{
    result = result + " " + num.substring(0,gap_size); // Insert space character
    num = num.substring(gap_size);  // Trim String
}

alert(result) // "123 456 789"

JSFiddle

Luminaire
  • 334
  • 6
  • 11
3

Use a regex with split() like

console.log('123456789'.split(/(\d{3})/).join(' ').trim());
AmmarCSE
  • 30,079
  • 5
  • 45
  • 53
2

You could:

var formatted = str.replace(/(\d{3})/g, '$1 ').trim();
Alex K.
  • 171,639
  • 30
  • 264
  • 288
0

Try to design a pattern like this.

function numberWithSpaces(value, pattern) {
  var i = 0,
    sequence = value.toString();
  return pattern.replace(/#/g, _ => sequence[i++]);
}

console.log(numberWithSpaces('123456789', '### ### ###'));
Penny Liu
  • 15,447
  • 5
  • 79
  • 98
-1

You can use a regex for that

var a = "123456789"
a.match(/\d{3}/g).join(" ")
> "123 456 789"

The regex matches a group of 3 digits several times

gusridd
  • 864
  • 10
  • 16