简体   繁体   English

如何使用 JavaScript 在数字之间添加空格?

[英]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?对于像123456789这样的输入,如何使用 JavaScript 将其转换为像123 456 789这样的格式?

split("").join(" "); returns 1 2 3 4 5 6 7 8 9 .返回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 $ (?=pattern)是前瞻, \\d{3}是 3 位数字, (pattern)+表示重复最后一个模式一次或多次(贪婪地)直到字符串$的结尾

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 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正则表达式多次匹配一组 3 位数字

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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