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 :).
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 🙂
LikeLike
@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.
LikeLike
Sweet. Thanks.
LikeLike
Awesome! Big thanks!
LikeLike
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;
};
LikeLike
Erg… sorry about the non-indented code. I put it up on github
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
strPad.js
hosted with ❤ by GitHub
LikeLike
Excelente muy buen aporte…
LikeLike