a blog by Christian Snodgrass
about programming, web and game design, and everything else

Padding String in Javascript

Yesterday when I was working on a little Javascript for showing all unicode characters yesterday, I needed a way to pad the string. I did a bit of research and came across a very interesting and handy approach.

The Typical Approach

The typical approach is pretty simple. You create a loop and just add whatever your pad character is as much as you need. Here is an example of a function which pads the left side of the string.

/** 
@param str - The string to pad. 
@param padChar - The character to pad the string with. 
@param length - The length of the resulting string. 
@return The padded string. 
*/ 
function padLeft(str, padChar, length) { 
    while(str.length < length) 
        str = padChar + str; 
    return str; 

This approach works, but it can be a bit of overkill. Sometimes you just want to pad one little thing really quick. That’s where this handy inline padding trick works.

Inline Padding with slice

For those of you not familiar with it, the slice() function (which is part of String) takes a start and option end, and slices the string to that size, and then returns it. Here are some examples:

var myStr = "abcdef"; 
 
// Starts at index of 2, so shows "cdef" 
alert(myStr.slice(2)); 
 
// Starts at index 2 and ends before index 
// 4, so returns "cd". 
alert(myStr.slice(2, 4)); 
 
// Starts at the end and goes back 3, 
// so we get "def". 
alert(myStr.slice(-3)); 

The second and third usage are the ones we’re interested in at the moment.

Padding the Right

So, to pad the right, all we have to do is add whatever our padding characters to the string, enough to go the full length of our padding. Then, we’ll slice off the extra.

Say we want to have some hyphens to divide up our sections by making each title be 20 characters long. All we have to do is create a string with 20 characters long, add it to the end of our title string, and then slice, like so:

var title = "Hello World"; 
 
// Alerts "Hello World---------" 
alert((title + "--------------------").slice(0, 20)); 

A nice and simple padding string, all done in one line!

Padding the Left

Padding the left is very similar, we just flip some things around. Say we want to have some numbers and we want them to be 5 digits long, and contain preceding zeros if there aren’t enough digits.

In this case, we’ll add the zeros to the beginning, and then use slice with a negative start to take the numbers we want.

var num = 23; 
alert(("00000" + num).slice(-5)); // Alerts "00023" 

Super simple.

A Bit More Complex

Just to round out this article on padding, let’s say you are building a Javascript application and want a flexible padding function. In this case, a loop is a good option, allowing us to handle any character. Let’s also say we want one function that can handle both padding left and padding right. We’ll also say we want to be able to use multiple characters for the padding (such as a repeating sequence of “ab”).

Let’s take a look at what we’ll need to build this function.

The Function Definition

First, we’ll create our function shell. For this, we know we’ll need a couple of parameters:

Most of those are straight forward. The only way we have some question about. To keep things simple, we’ll just use the value -1 to mean left, 0 to mean both sides, and 1 to mean right. If you wanted to get fancy, you could create some variables to represent each one (like constants in most languages, which Javascript lacks).

/** 
@param str - The string we are padding. 
@param dir - The direction we are padding (-1: left, 0, even, 1: right). 
@param chars - The characters we're padding with. 
@param length - The length of the final string. 
*/ 
function pad(str, dir, chars, length) { 

That looks like a good start.

The Padding Loop

For the actual padding, we’ll use a loop just like we did before. The difference this time is we’ll have two if statements to determine if we’re padding left or right. If it’s even, we’ll just make it do both sides at the same time. Our if statements will see if it’s less than or greater than 0 to determine, which means you can technically pass any number… a bit more flexible and a couple characters shorter code.

while(str.length < length) { 
    if(dir <= 0)      
        str = str + chars;    
    if(dir >= 0) 
        str += chars; 

Once we exit that loop, our string will be greater than or equal to the length we want to achieve. However, because it may be greater, we’ll need to trim it down a wee bit.

Trimming the Padded String

Our last step is to trim off the string of it’s extra characters. To do this, we’ll make use of the slice function to do it in one quick swing. We can do our slicing in one line, like so:

return str.slice((dir >= 0 ? dir == 0 ? Math.floor((str.length - length) / 2) : str.length - length : 0)).slice(-length); 

The first slice does the slicing of the right side (using a positive start value). The second slice does the slicing of the left side (using a negative start value).

For those of you not used to the that conditional structure (especially nested), it can look weird. Essentially, in Javascript (and many other languages), there is a kind of shorthand inline if statement that looks like this:

(condition ? true_value : false_value) 

It also gives values, instead of doing statements. In this case, we have two of them. To understand a bit simpler, here is that line rewritten with standard if statements:

// If we're doing a right or even pad 
if(dir >= 0) 
    // If we're doing an even pad 
    if(dir == 0) 
        // Use half the difference between the current length 
        // and the desired length, with the decimal cut off. 
        val = (str.length - length) / 2; 
    else 
        // Use the whole difference between the 
        // current and desired lengths. 
        val = str.length - length; 
else 
    // Not slicing the right at all. 
    val = 0; 

The second slice is much simpler: we only want our string to be length-long, so we’ll take only that much.

All Together

Here is the function all together:

/** 
@param str - The string we are padding. 
@param dir - The direction we are padding (-1: left, 0, even, 1: right). 
@param chars - The characters we're padding with. 
@param length - The length of the final string. 
*/ 
function pad(str, dir, char, length) { 
    while(str.length < length) { 
        if(dir <= 0) 
            str = char + str; 
        if(dir >= 0) 
            str += char; 
 
    return str.slice((dir >= 0 ? dir == 0 ? (str.length - length) / 2 : str.length - length : 0)).slice(-length); 

Not bad for such a flexible function. There is one more thing we could do to make it even more useful, prototype it to the String object.

Prototyping to the String Object

Prototyping allows us to attach our function to an existing object, so install of calling it like:

pad(myStr, 0, "0", 10);

We can call it like this:

myStr.pad(0, "0", 10);

This step is really optional, and up to personal preference. I prefer to go the object-oriented route, so we’ll prototype.

To prototype it, we really only need to make three small changes:

Prototype the Function

For this, all we have to do is add one line after our function:

String.prototype.pad = pad;

Now it’s attached to our string.

Remove the Parameter

This is super simple, just remove the “str” from the function definition.

Get Value of String

Since our function is now attached to the string, we get the value of that string with “this”. However, we can’t set “this” equal to anything in our function, which is okay with us. We’ll just add one line to the top of our function and everything else can stay the same:

var str = this;

Now str has the value of this, and the rest of our function performs as it did before.

The Completed Function

And here it is:

/** 
@param str - The string we are padding. 
@param dir - The direction we are padding (-1: left, 0, even, 1: right). 
@param chars - The characters we're padding with. 
@param length - The length of the final string. 
*/ 
function pad(dir, char, length) { 
    var str = this; 
         
    while(str.length < length) { 
        if(dir <= 0) 
            str = char + str; 
        if(dir >= 0) 
            str += char; 
 
    return str.slice((dir >= 0 ? dir == 0 ? (str.length - length) / 2 : str.length - length : 0)).slice(-length); 
 
String.prototype.pad = pad; 

To use the function, all we have to do is take any string and call our pad function:

var myStr = "abc"; 
 
// 0 means even, so we get "---abc---". 
alert(myStr.pad(0, "-", 9)); 

Hope you found this little lesson helpful for all your padding needs.


Related Articles


Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>


Back to Top