javascript string padding function

javascript string object doesn’t come with string padding function. Here is a a string padding function that takes three parameters, string, width and padding. It converts the string to a string of the specified width and padding.
[code language=”javascript”]
function strPad(str, width, padding) {
if (typeof str === ‘string’ || typeof str === ‘number’) {
str = str + ”;
} else {
throw ‘str has to be type string or number.’;
}

if (typeof width !== ‘number’) {
throw ‘width has to be a number.’;
}

if (typeof padding !== ‘string’) {
throw ‘padding has to be a string.’;
}

if (padding.length === 0) {
throw ‘padding cannot be an empty string.’;
}

while (str.length < width) {
str = padding + str;
}
return str;
}
[/code]

Examples:
[code language=”javascript”]
var strings = [‘1222′,123,""];
for(var i=0; i<strings.length; i++) {
console.log(strPad(strings[i],10,’0′));
}
console.log(strPad("111",10,’0′));
console.log(strPad("222",-2,’ ‘));
console.log(strPad("333",0,’ ‘));

// outputs:
// 0000001222
// 0000000123
// 0000000000
// 0000000111
// 222
// 333
[/code]

Search within Codexpedia

Custom Search

Search the entire web

Custom Search