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 :) .

5 thoughts on “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. Pingback: [jQuery] String formatieren - Delphi-PRAXiS

  3. Pingback: How to add leading zeroes in a php variable « Data Integrated Entity

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>