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
.
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
.
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 $
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"
Use a regex with split()
like
console.log('123456789'.split(/(\d{3})/).join(' ').trim());
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', '### ### ###'));
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