简体   繁体   English

如何使用 JavaScript 为每两个数字添加空格?

[英]How to add spaces to every two numbers with JavaScript?

I like to output a formatted number with a space after every two numbers, I've tried this:我喜欢在每两个数字后输出一个带空格的格式化数字,我试过这个:

 function twoSpaceNumber(num) {
    return num.toString().replace(/\B(?<!\.\d)(?=([0-9]{2})+(?!\d))/g, " ");
}

twoSpaceNumber(12345678) => 1 23 45 67 89 ( should start with 12 ? ) twoSpaceNumber(12345678) => 1 23 45 67 89 (应该从 12 开始?)

and also when it starts with 0 I had very strange output而且当它以 0 开头时,我有非常奇怪的输出

twoSpaceNumber(012345678) => 12 34 56 78 twoSpaceNumber(012345678) => 12 34 56 78

Please consider请考虑

var s = "1234456";
var t = s.match(/.{1,2}/g);
var u = t.join(" ");
console.log(u);

which logs哪些日志

12 34 45 6 12 34 45 6

and

var s = "ABCDEF";
var t = s.match(/.{1,2}/g);
var u = t.join(" ");
console.log(u);

which logs哪些日志

AB CD EF AB CD EF

Note that s is a string.请注意, s一个字符串。

Is that what you need?那是你需要的吗?

Pass num as a string, not a number, else the leading zeros will disappear and usenum作为字符串而不是数字传递,否则前导零将消失并使用

function twoSpaceNumber(num) {
  return num.replace(/\d{2}(?!$)/g, "$& ");
}

The regex matches two digits that are not at the end of string (in order not to add a space at the string end).正则表达式匹配不在字符串末尾的两个数字(为了不在字符串末尾添加空格)。

JavaScript demo JavaScript 演示

 const regex = /\\d{2}(?!$)/g; function twoSpaceNumber(num) { return num.replace(regex, "$& "); } const strings = ['123456789','012345678']; for (const string of strings) { console.log(string, '=>', twoSpaceNumber(string)); }

If you don't mind a non-regex approach:如果您不介意非正则表达式方法:

function twoSpaceNumber(num) { 
    var res = '';
    num += '';
    for(var i = 0; i < num.length; i+=2)
    {    
        res += num.substr(i,2) + ' ';
    }
    return res.trim();
}

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

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