问题描述:

The problem:

In my database I keep some account numbers in form:

PL83102044760000870200961284

Now I have to format it like this:

PL 83 1020 4476 0000 8702 0096 1284

I wrote simple js regex that do the job:

account.replace(/(\w{2})(\d{2})(\d{4})(\d{4})(\d{4})(\d{4})(\d{4})(\d{4})/g, '$1 $2 $3 $4 $5 $6 $7 $8');

But I fell this is somehow naive solution and this code can be refactored to avoid repetitions. Anyone can do this shorter?

网友答案:

Something like

"PL83102044760000870200961284".match(/.{4}/g).join(" ")

maybe?

Didn't notice the first requirement of "PL 83"

account.match(/.{4}/g).map(function(n){ return /([A-Z]{2})(\d{2})/.test(n) ? RegExp.$1 + " " + RegExp.$2 : n; }).join(" ");

To be honest, i would be tempted just to manually fix tat first bit rather than map, or i'm sure there's clever way to use match to do both...

This works too

account.match(/[A-Z]{2}|(?:(?:\d{2}|\d{4})(?=(\d{4})*$))/g).join(" ")
网友答案:

Oh boy, once again regex when it is not needed at all.

function getFormattedAccountNo( accountNo ){

    var formattedAccountNo = '';
    for ( var i = 0; i < accountNo.length; i++ ){
         if ( formattedAccountNo.length == 2 || formattedAccountNo.length % 4 == 0 ){ 
             formattedAccountNo += ' ';
         }
         formattedAccountNo += accountNo.charAt(i);
    }
    return formattedAccountNo;
}
网友答案:

This solution may be a little tricky :

"PL83102044760000870200961284".replace(/^(\w{2})(\d{2})(\d{24})$/, function(_, a, b, c) {
    return [a, b, c.replace(/(\d{4})/g, '$1 ')].join(" ");
});
网友答案:

It's not the best looking of solutions, but I agree with scibuff: Regular expressions are not the way to go in this case... here's a simple 1 line solution:

var str = 'PL83102044760000870200961284';
var formatted = str.substr(0,2)+' '+str.substr(2,2)+' '+str.substr(4,4)+' '+str.substr(8,4)+' '+str.substr(12,4)+' '+str.substr(16,4)+' '+str.substr(20,4)+' '+str.substr(24);

Console output: "PL 83 1020 4476 0000 8702 0096 1284".

相关阅读:
Top