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

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 with a JavaScript array.

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.

Published on Feb 23, 2019

Tags: JavaScript | jQuery Tutorial

Related Posts

Did you enjoy this article? If you did here are some more articles that I thought you will enjoy as they are very similar to the article that you just finished reading.


Learn how to code in HTML, CSS, JavaScript, Python, Ruby, PHP, Java, C#, SQL, and more.

No matter the programming language you're looking to learn, I've hopefully compiled an incredible set of tutorials for you to learn; whether you are beginner or an expert, there is something for everyone to learn. Each topic I go in-depth and provide many examples throughout. I can't wait for you to dig in and improve your skillset with any of the tutorials below.