Pad A String In JavaScript Using Augmentation

Ever needed to pad a string in JavaScript with a certain character? This article will describe a simple extension to the String prototype that will do just that! -Perhaps with a bit more flexibility.

To get right to the point, here is the implementation:

if ( "undefined" === typeof String.prototype.pad ) {
    String.prototype.pad = function _String__pad ( obj ) {
        var result = this,
            width = 2,
            padChar = "0",
            prefix = false;

        if ( obj ) {
            if ( "object" === typeof obj ) {
                if ( obj.prefix ) { prefix = obj.prefix };
                if ( obj.width ) { width = obj.width };
                if ( obj.char ) { padChar = obj.char };
            } else if ( "string" === typeof obj ) {
                padChar = obj;
            } else if ( "number" === typeof obj ) {
                width = obj;
            }
        }

        while ( this && width > result.length ) {
            if ( prefix ) {
                result = padChar + result;
            } else {
                result += padChar;
            }
        }

        return result;
    };
}

Before I get to the guts of the above code snippet, I wish to examine a few reasons it is possible:

  • Instance methods can be created on-the-fly. This means a String object such as “Hello World” would immediately contain the above method named “pad”. The method could be called like “Hello World”.pad().
  • JavaScript is a dynamic language. In this case, it means any variable can be of any type at any point during runtime.
  • A method exists as a “function”. This can be explicitly tested.
  • Instance methods exist in an Object’s prototype.

Now for the details.

First, it is always wise to make sure your code is not performing unnecessary work. To this end a check is made to make sure the function does not already exist on String’s prototype. If it does not already exist, it is created.

Four variables are then declare presenting the features of this method:

  • Returns a new string
  • Supports a custom string width
  • Supports a custom padding character
  • Supports either prefix padding or suffix padding

These variables are optionally overridden by the object, String, or Number argument given. This is one of many times when the beauty of JavaScript’s weakly-typed nature really shines. Any of the features can be overridden given the appropriate argument type and value. If the argument is an object, the method expects the object to contain the three properties: prefix, width, and char. If the argument is a String the method assumes the client is attempting to override the padding character. If the argument is a number, the method assumes the client is attempting to override the padded string width.

Lets talk more about the padded string width. This is important for the next bit of code.

Assume there is a string indicating an order number of “99D”. The requirements say order numbers less than 5 characters must be padded on the left with zeros. The implementation supports this:

"99D".pad({ char: "0", width: 5, prefix: true }); //result: "0099D"

-or-

var orderNumber = "99D";
orderNumber.pad({ char: "0", width: 5, prefix: true }); //result: "0099D"

-or-

var padOptions = { char: "0", width: 5, prefix: true };
"99D".pad(padOptions); //result: "0099D"

To get this set width, a while loop is used. While the string is less than the given width, the method adds the specified pad character to either the beginning or the end of the string based on whether it should be a prefix or not. Once the string is at least the length of the specified padded string width, the method breaks out of the while loop and returns the resultant string.

There are other ways to use this implementation of the pad method as well:

Specify the padding character –

"E".pad("T"); //result: "ET"

Specify the padded string width –

"1".pad(2); //result: "10"

There are a few improvements or additional features that could be implemented for this method but, this is a flexible start.

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s