在Javascript中对齐或填充这些字符串中的一些内容

Align or pad some content in these strings in Javascript

本文关键字:字符串 Javascript 对齐 填充      更新时间:2023-09-26

我有以下字符串:

14/04/14     13:31:38     12.54N     88.21W     106.8     3.8ML     Frente al Golfo de Fonseca
14/04/14     11:56:04     11.27N     86.98W     15.2     2.9ML     Frente a Masachapa
14/04/13     11:17:30     12.60N     86.80W     0.2     0.7ML     Cerca del volcan Telica

我想把它们转换成这个:

14/04/14     13:31:38     12.54N     88.21W     106.8     3.8ML     Frente al Golfo de Fonseca
14/04/14     11:56:04     11.27N     86.98W      15.2     2.9ML     Frente a Masachapa
14/04/13     11:17:30     12.60N     86.80W       0.2     0.7ML     Cerca del volcan Telica

想要用Javascript中的正则表达式来实现。

注1:目标是对齐"第五列"中的数据,如您所见,要对齐的模式是. 的第三次出现

注意2:每一行都是独立的(我在一个数组中有每一行)我放了不止一行来显示不同类型的场景,因为最后我需要打印出所有的行。

非常感谢!

您可以尝试每一行:

line = line.replace(/^((?:'s*'S+){4})'s+?(['s'd]{5}'.)/, "$1    $2");

方法是在以句点结束的固定长度子模式之前使用惰性量词。

注意:只有当数字有一个小数点并且位数在2到6之间时才有效 (从0.1到99999.9)

如果没有一个正则表达式,这是一个非常困难的方法,它会检查每个要检查的列中长度最长的字符串,然后相应地填充。它没有以任何方式说明数字中的周期,它只是根据长度添加填充

function tabulate(arr, sep, col) {
    var cols = [];
    arr.forEach(function(str) {
        str.split(sep).forEach(function(part, i) {
            Array.isArray(cols[i]) ? cols[i].push(part) : cols[i] = [part];
        });
    });
    cols.forEach(function(arr2, i) {
        if (col.indexOf(i) != -1) {
            var padd = arr2.slice().sort(function(a,b) {
                return a.length - b.length;
            }).pop().length + 1;
            arr2.forEach(function(itm, i2) {
                cols[i][i2] = (new Array(padd - itm.length)).join(' ') + itm;
            });
        }
    });
    return arr.map(function(itm, j) {
        return cols.map(function(itm2) {
            return itm2[j];
        }).join(sep);
    });
}

用作

tabulate( array, separator string, [columns to apply function to (zero based)] )

在这种情况下相当于

tabulate(arr, '     ', [4]);

FIDDLE