2009-10-19

Pad Text

The XML encoding and decoding functions posted yesterday call a function pad() which is below.

Padding is the process of adding extra text to ( typically ) the front of a string of numbers to make the string a certain length.
This is a generic function to pad any thing that can be converted to a string to a specified count of digits.
It is unique in that it allows anything to be used as a pad character, though zero padding is the default.

Called by the of epsEntitify() function. That posting can be found here.

function pad ( orig , count , padWith ) {
//-------------------------------------------------------------------------
//-- P A D
//-------------------------------------------------------------------------
//-- Generic: Yes!
//-------------------------------------------------------------------------
//-- Purpose: to pad the 'orig' number or string to a fixed 'count'
//-- characters or digits using the 'padWith' character
//-------------------------------------------------------------------------
//-- Returns a string (even if it doesn't need to be padded)
//-------------------------------------------------------------------------
//-- Sample Calls:
//-- p = pad (7,3,0) ; // '007'
//-- p = pad (21,1) ; // '21'
//-- p = pad ('Right',10,' ') ; // ' Right'
//-- p = pad ('Left',0,' ' ) ; // 'Left'
//-------------------------------------------------------------------------
//-- Written 2009.05.01 at the PDX airport by Jon S. Winters
//-- eps@electronicpublishingsupport.com
//-------------------------------------------------------------------------
//-- Check arguments
//--default of zero as string
var padChar = "0" ;
//-- but if they sent something, use the first character of it
if ( padWith != undefined ) { padChar = String (padWith).substr (0,1) ; }
//-- Convert to a string (actually adding the "" to it would have worked.)
var withThis = String ( orig ) + '' ;
//-- Check its length, with it is long enought return. Until then keep
//-- adding the padChar
while ( count > withThis.length) {
withThis = padChar + withThis;
}
//-- Back to the caller
return withThis;
}
//

No comments:

Post a Comment