Follow @endyourif rss Facebook LinkedIn

jQuery: Padding a Variable or String with a Specific Character jQuery: Padding a Variable or String with a Specific Character

Published on Feb 23, 2019

Every so often you will receive data from a database or potentially user input, but a specific number of characters might be required to format or display the data properly. As an example, you may wish to ensure that a number less than 9 is prefixed with a 0 where numbers that are 10 or more do not need the padding. By extending jQuery, two functions can be created to either prefix or postfix a specific value to a DOM element using a jQuery selector.

To start, here is an example of the starting input and the ending output:

Input: Some text
Output: Some text*****************************************

Input: Some more text
Output: ************************************Some more text

Output: 09

Input: 50
Output: 50

Leveraging $.extend() and this.each

In the first and second example, an asterisk is being prefixed and postfixed, respectively, to fill in up to 50 characters of text. The last two examples, prefix the numbers with a 0 if the length is less than 2. Now to the code:

(function($) {
$.extend($.fn, {

prefixString: function(value, length) {
var $this = this;
return this.each(function() {
$(this).text($this.padString(value, $(this).text().length, length) + $(this).text());

postfixString: function(value, length) {
var $this = this;
return this.each(function() {
$(this).text($(this).text() + $this.padString(value, $(this).text().length, length));

padString: function(value, minLength, maxLength) {
var newString = "";
for (var x = minLength; x < maxLength; x++) {
newString += value;

return newString;


The above jQuery extension contains three functions. The first two are the ones that will allow you to prefix or postfix the string to the contents of an HTML element's text contents. The following extension can be used in the following way:

$("#test1").postfixString('*', 50);
$("#test2").prefixString('*', 50);
$("#test3").prefixString('0', 2);
$("#test4").prefixString('0', 2);

some text
some more text

By extending jQuery, we can enable our basic JavaScript code to pad a jQuery element with a specific value to a specific length with a single function call.

Tags: JavaScript | jQuery Tutorial | padding | each

My Books
ASP.NET MVC 5 With Bootstrap and Knockout.js
Knockout.js Building Dynamic Client-Side Applications
20 Recipes for Programming MVC 3
20 Recipes for Programming PhoneGap
Rapid Application Development with CakePHP