A common jQuery extension code was written when a formatting amount problem occurred in the project a few days ago and recorded for later use. At the same time, I would like to share with you what you need.
If some experts think that writing is efficient, they can also propose, study, and research.
In addition to numbers, strings can also be formatted. After all, the principle is similar! You can customize the delimiter, split the length, and finally return the formatted string.
I. jQuery extension code
Copy to ClipboardReference: [www.bkjia.com]; (function ($ ){
$. Extend ({
Format: function (str, step, splitor ){
Str = str. toString ();
Var len = str. length;
If (len> step ){
Var l1 = len % step,
L2 = parseInt (len/step ),
Arr = [],
First = str. substr (0, l1 );
If (first! = ''){
Arr. push (first );
};
For (var I = 0; I <l2; I ++ ){
Arr. push (str. substr (l1 + I * step, step ));
};
Str = arr. join (splitor );
};
Return str;
}
});
}) (JQuery );
Ii. Call Method
Copy to ClipboardReference: [www.bkjia.com] jQuery (function (){
Console. log ($. format (2000000010, 3, ','); // result: 2,000,000,010
Console. log ($. format ('abcdefhijklmnopqrstuvwxy', 6, '-'); // result: AB-cdefgh-ijklmn-opqrst-uvwxyz
});