String Formatting

by bladnman

HTML

<script src="https://raw.github.com/carhartl/jquery-cookie/master/jquery.cookie.js"></script>
<input type=button id="theButton" value="run test" class="runButton">

<div id="log" class="log"></div>

CSS

.runButton {
    width:   125px;
    margin:  20px;
}
.log {
   padding:10px; 
    margin: 20px; 
    border: 1px dotted #ccc; 
    color:#888; 
    font-face: arial; 
    font-size:12px; 
    background: #fbfbfb; 
}

JavaScript

/* ************************************ */

function runTest() {
    debug("test running");

    var outFormat = "{0}-{2}-{4}";
    var str = new String("Hello");   
    
    
    debug(outFormat.format(str));
    debug(outFormat.format( "A", "B", "C" ));
    debug(outFormat.format( ["A", "B", "C"] ));
    debug(outFormat.format( str.split('') ));
}

String.prototype.format    = function() {
    var args                = arguments;
    if (typeof args == 'undefined' || args == null || args.length < 1) {
        return this;
    }

    var firstArg            = args[0];
    var firstArgType        = toType(firstArg);
    var isArray                = false;
    if (firstArgType == "array") {
        isArray                = true;
    }

    // INDIVIDUAL ARGS TO REPLACE WITH
    if (!isArray) {
        return this.replace(/{(\d+)}/g, function(match, number) {
                    return typeof args[number] != 'undefined'
                            ? args[number]
                            : match;
                });
    }

    else {
        var theArray = firstArg;
        return this.replace(/{(\d+)}/g, function(match, number) {

                    if (number > theArray.length) {
                        return match;
                    }

                    return typeof theArray[number] != 'undefined'
                            ? theArray[number]
                            : match;
                });
    }
};


function toType(obj) {
    return ({}).toString.call(obj).match(/\s([a-z|A-Z]+)/)[1].toLowerCase();
}


/* ************************************ 
 _____ ___ __  __ ___ _      _ _____ ___ 
|_   _| __|  \/  | _ \ |    /_\_   _| __|
  | | | _|| |\/| |  _/ |__ / _ \| | | _| 
  |_| |___|_|  |_|_| |____/_/ \_\_| |___|
                                         
************************************  */

    function debug(message, value) {
        var outMessage = message;

        if (typeof value !== "undefined" && value !== null) {
            outMessage...