简体   繁体   中英

How to add spaces between numbers with JavaScript?

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"

JSFiddle

你可以:

var formatted = str.replace(/(\d{3})/g, '$1 ').trim();

使用带有split()的正则表达式,例如

 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM