27th February 2009

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.

1
2
3
4
5
6
7
8
$.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 :) .

3 Responses to “Simple jQuery string padding function”

  1. Wardy says:

    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. Steve says:

    @Wardy: Thanks :) – There is actually an open source project (PHP.js) available at http://phpjs.org/ that is attempting to port suitable PHP functions to JavaScript.

Leave a Reply

Categories

Twitter

About Me

“I have a geek lifestyle, except geeks don’t have a life. Or style!”

Hi, my name is Steve and this is my blog. I am a web developer based in the United Kingdom. I like (X)HTML, CSS, Flash, ActionScript3, PHP, JavaScript, MySQL, [paste trendy words here] and Mapping APIs.