Simple jQuery string padding function

I’ve written a very simple jQuery function to return a string padded to a specified length, similar to the php equivalent str_pad.

$.strPad = function(i,l,s) {
	var o = i.toString();
	if (!s) { s = '0'; }
	while (o.length < l) {
		o = s + o;
	}
	return o;
};

Example Usage:

$.strPad(12, 5); // returns 00012
$.strPad('abc', 6, '#'); // returns ###abc

This version only supports left padding, which is why it is labelled as only a simple version :).

9 Replies to “Simple jQuery string padding function”

  1. This is great, there are a lot of PHP-related scripting functions that would be handy if they were accessible in JavaScript – this takes us a step closer!

    As you mention, the option to choose which side of the text to pad would also be great 🙂

  2. Thanks a ton for the code. I went ahead and modified & expanded it to act exactly like the php str_pad version:

    $.strPad = function(input, pad_length, pad_string, pad_type){
    var output = input.toString();
    if (!pad_string) { pad_string = ‘ ‘; }
    if (pad_type === undefined) { pad_type = ‘STR_PAD_RIGHT’; }
    if (pad_type == ‘STR_PAD_RIGHT’) {
    while (output.length < pad_length) {
    output = output + pad_string;
    }
    } else if (pad_type == 'STR_PAD_LEFT') {
    while (output.length < pad_length) {
    output = pad_string + output;
    }
    } else if (pad_type == 'STR_PAD_BOTH') {
    var j = 0;
    while (output.length < pad_length) {
    if (j % 2) {
    output = output + pad_string;
    } else {
    output = pad_string + output;
    }
    j++;
    }
    }
    return output;
    };

Leave a Reply