[英]How to add spaces between numbers with JavaScript?
對於像123456789
這樣的輸入,如何使用 JavaScript 將其轉換為像123 456 789
這樣的格式?
split("").join(" ");
返回1 2 3 4 5 6 7 8 9
。
如果您總是希望空間距離您的右側有多遠,請使用以三為單位計數的前瞻
'12345678'.replace(/(\d)(?=(\d{3})+$)/g, '$1 '); // "12 345 678"
(?=pattern)
是前瞻, \\d{3}
是 3 位數字, (pattern)+
表示重復最后一個模式一次或多次(貪婪地)直到字符串$
的結尾
使用子串方法:
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"
你可以:
var formatted = str.replace(/(\d{3})/g, '$1 ').trim();
使用帶有split()
的正則表達式,例如
console.log('123456789'.split(/(\\d{3})/).join(' ').trim());
嘗試設計這樣的模式。
function numberWithSpaces(value, pattern) { var i = 0, sequence = value.toString(); return pattern.replace(/#/g, _ => sequence[i++]); } console.log(numberWithSpaces('123456789', '### ### ###'));
您可以為此使用正則表達式
var a = "123456789"
a.match(/\d{3}/g).join(" ")
> "123 456 789"
正則表達式多次匹配一組 3 位數字
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.