powered by Slim Framework
enhanced by Nesbot.com

jQuery: Padding a Variable or String with a Specific Character

Published on Jan 30, 2012 by Jamie Munro

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:



















Some text Some text*****************************************
Some more text ************************************Some more text
9 09
50 50

 

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;
}

});
})(jQuery);


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:


<script>
$(document).ready(function() {
$("#test1").postfixString('*', 50);
$("#test2").prefixString('*', 50);
$("#test3").prefixString('0', 2);
$("#test4").prefixString('0', 2);
});
</script>

<div id="test1">some text</div>
<div id="test2">some more text</div>
<div id="test3">5</div>
<div id="test4">50</div>

Summary


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

<- CSS3: Creating a Background Gradient  Home MVC 3: Pass Model or Form Data through a Redirect -> 
blog comments powered by Disqus