Fork me on GitHub

Namespace comb.string

String utilities
Defined in: string.js.

Namespace Detail
comb.string
/**
 * Pads a string
     *
     * @example
     *
     * comb.string.pad("STR", 5, " ", true) => "STR  "
     * comb.string.pad("STR", 5, "$") => "$$STR"
     *
     * @param {String} string the string to pad
     * @param {Number} length the length of the string when padded
     * @param {String} [ch= " "] character to pad the string with
     * @param {Boolean} [end=false] if true then the padding is added to the end
     *
     * @returns {String} the padded string
     */
pad : function(string, length, ch, end) {
    string = "" + string; 
    ch = ch || " ";
    var strLen = string.length;
    while (strLen < length) {
        if (end) {
            string += ch;
        } else {
            string = ch + string;
        }
        strLen++;
    }
    return string;
},

/**
 * Truncates a string to the specified length.
     * @example
     *
     * //from the beginning
     * comb.string.truncate("abcdefg", 3) => "abc";
     * //from the end
     * comb.string.truncate("abcdefg", 3,true) => "efg"
     * //omit the length
     * comb.string.truncate("abcdefg") => "abcdefg"
     *
     * @param {String} string the string to truncate
     * @param {Number} [length = -1] the max length of the string, if the string is
     *                              shorter than the length then the string is returned.
     * @param {Boolean} [end=false] truncate starting at the end of the string
     *
     * @return {String} the truncated string.
     */
truncate : function(string, length, end) {
    var ret = string;
    if (comb.isString(ret)) {
        if (string.length > length) {
            if (end) {
                var l = string.length;
                ret = string.substring(l - length, l);
            } else {
                ret = string.substring(0, length);
            }
        }
    } else {
        ret = comb.string.truncate("" + ret, length);
    }
    return ret;
},

/**
 * Formats a string with the specified format
     *
     * @example
     *
     *  var format = comb.string.format;
     *
     *  format("%s, %s", ["Hello", "World"]) => "Hello, World";
     *  format("%[ 10]s, %[- 10]s", ["Hello", "World"])
     *      => "     Hello, World     ";
     *  format("%-!10s, %#10s, %10s and %-10s",
     *                          "apple", "orange", "bananas", "watermelons")
     *      => "apple!!!!!, ####orange,    bananas and watermelon"
     *  format("%+d, %+d, %10d, %-10d, %-+#10d, %10d",
     *                          1,-2, 1, 2, 3, 100000000000)
     *      => "+1, -2, 0000000001, 2000000000, +3########, 1000000000"
     *  format("%[h:mm a]D", [date]) => 7:32 PM - local -
     *  format("%[h:mm a]Z", [date]) => 12:32 PM - UTC
     *  //When using object formats they must be in an array otherwise
     *  //format will try to interpolate the properties into the string.
     *  format("%j", [{a : "b"}])
     *      => '{"a":"b"}'
     *  format("%1j, %4j", [{a : "b"}, {a : "b"}])
     *      => '{\n "a": "b"\n},\n{\n    "a": "b"\n}'
     *  format("{hello}, {world}", {hello : "Hello", world : "World")
     *      => "Hello, World";
     *  format({[-s10]apple}, {[%#10]orange}, {[10]banana} and {[-10]watermelons}",
     *                      {
     *                          apple : "apple",
     *                          orange : "orange",
     *                          banana : "bananas",
     *                          watermelons : "watermelons"
     *        });
     *      => applesssss, ####orange,    bananas and watermelon
     *
     * @param {String} str the string to format, if you want to use a spacing character as padding (other than \\s) then put your format in brackets.
     *  <ol>
     *      <li>String Formats %[options]s</li>
     *          <ul>
     *              <li>- : left justified</li>
     *              <li>Char : padding character <b>Excludes d,j,s</b></li>
     *              <li>Number : width</li>
     *          </ul>
     *      </li>
     *      <li>Number Formats %[options]d</li>
     *          <ul>
     *              <li>- : left justified</li>
     *              <li>+ : signed number</li>
     *              <li>Char : padding character <b>Excludes d,j,s</b></li>
     *              <li>Number : width</li>
     *          </ul>
     *      </li>
     *      <li>Object Formats %[options]j</li>
     *          <ul>
     *              <li>Number : spacing for object properties.</li>
     *          </ul>
     *      </li>
     *  </ol>
     *
     *
     * @param {Object|Array|Arguments...} obj the parameters to replace in the string
     *                                    if an array is passed then the array is used sequentially
     *                                    if an object is passed then the object keys are used
     *                                    if a variable number of args are passed then they are used like an array
     *
     * @returns {String} the formatted string
     */
format : function(str, obj) {
    !date && (date = require("./date"));
    if (obj instanceof Array) {
        var i = 0, len = obj.length;
        
        return str.replace(FORMAT_REGEX, function(m, format, type) {
            var replacer, ret;
            if (i < len) {
                replacer = obj[i++];
            } else {
                
                
                return m;
            }
            if (m == "%s" || m == "%d" || m == "%D") {
                
                ret = replacer;
            }else if(m == "%Z"){
                ret = replacer.toUTCString();
            } else if (m == "%j") {
                try {
                    ret = JSON.stringify(replacer);
                } catch(e) {
                    throw new Error("comb.string.format : Unable to parse json from ", replacer);
                }
            } else {
                format = format.replace(/^\[|\]$/g, "");
                switch (type) {
                    case "s":
                        ret = formatString(replacer, format);
                        break;
                    case "d":
                        ret = formatNumber(replacer, format);
                        break;
                    case "j":
                        ret = formatObject(replacer, format);
                        break;
                    case "D":
                        ret = date.date.format(replacer, format);
                        break;
                    case "Z":
                        ret = date.date.format(replacer, format, true);
                        break;
                }
            }
            return ret;
        });
    } else if (typeof obj == "object") {
        return str.replace(INTERP_REGEX, function(m, format, value) {
            value = obj[value];
            if (!misc.isUndefined(value)) {
                if (format) {
                    if (comb.isString(value)) {
                        return formatString(value, format);
                    } else if (typeof value == "number") {
                        return formatNumber(value, format);
                    } else if (date.isDate(value)) {
                        return date.date.format(value, format);
                    } else if (typeof value == "object") {
                        return formatObject(value, format);
                    }
                } else {
                    return "" + value;
                }
            }
            return m;
        });
    } else {
        var args = Array.prototype.slice.call(arguments).slice(1);
        return exports.string.format(str, args);
    }
},

/**
 * Converts a string to an array
     *
     * @example
     *
     * comb.string.toArray("a|b|c|d", "|") => ["a","b","c","d"]
     * comb.string.toArray("a", "|") => ["a"]
     * comb.string.toArray("", "|") => []
     *
     * @param {String} str the string to parse
     * @param {String} delimeter the delimeter to use
     */
toArray : function(testStr, delim) {
    var ret = [];
    if (testStr) {
        if (testStr.indexOf(delim) > 0) return testStr.replace(/\s+/g, "").split(delim);
        else return [testStr];
    }
    return ret;
},

/**
 * Returns a string duplicated n times;
     *
     * @example
     *
     * comb.string.multiply("HELLO", 5) => "HELLOHELLOHELLOHELLOHELLO"
     *
     *
     */
multiply : function(str, times) {
    var ret = [];
    if (times) {
        for (var i = 0; i < times; i++) {
            ret.push(str);
        }
    }
    return ret.join("");
},

/**
 * Styles a string according to the specified styles.
     *
     * @example
     * //style a string red
     * comb.string.style('myStr', 'red');
     * //style a string red and bold
     * comb.string.style('myStr', ['red', bold]);
     *
     * @param {String} str The string to style.
     * @param {String|Array} styles the style or styles to apply to a string.
     *          options include :
     *          <ul>
     *             <li>bold</li>
     *             <li>bright</li>
     *             <li>italic</li>
     *             <li>underline</li>
     *             <li>inverse</li>
     *             <li>crossedOut</li>
     *             <li>blink</li>
     *             <li>red</li>
     *             <li>green</li>
     *             <li>yellow</li>
     *             <li>blue</li>
     *             <li>magenta</li>
     *             <li>cyan</li>
     *             <li>white</li>
     *             <li>redBackground</li>
     *             <li>greenBackground</li>
     *             <li>yellowBackground</li>
     *             <li>blueBackground</li>
     *             <li>magentaBackground</li>
     *             <li>cyanBackground</li>
     *             <li>whiteBackground</li>
     *             <li>grey</li>
     *             <li>black</li>
     *
     *          </ul>
     */
style : function(str, options) {
    var ret = str;
    if (options) {
        if (ret instanceof Array) {
            ret = ret.map(function(s) {
                return comb.string.style(s, options);
            })
        } else if (options instanceof Array) {
            options.forEach(function(option) {
                ret = comb.string.style(ret, option);
            });
        } else if (options in styles) {
            ret = '\x1B[' + styles[options] + 'm' + str + '\x1B[0m';
        }
    }
    return ret;
}
Method Detail
<static> {String} comb.string.format(str, obj)
Formats a string with the specified format

Example 1 :

 var format = comb.string.format;

 format("%s, %s", ["Hello", "World"]) => "Hello, World";
 format("%[ 10]s, %[- 10]s", ["Hello", "World"])
     => "     Hello, World     ";
 format("%-!10s, %#10s, %10s and %-10s",
                         "apple", "orange", "bananas", "watermelons")
     => "apple!!!!!, ####orange,    bananas and watermelon"
 format("%+d, %+d, %10d, %-10d, %-+#10d, %10d",
                         1,-2, 1, 2, 3, 100000000000)
     => "+1, -2, 0000000001, 2000000000, +3########, 1000000000"
 format("%[h:mm a]D", [date]) => 7:32 PM - local -
 format("%[h:mm a]Z", [date]) => 12:32 PM - UTC
 //When using object formats they must be in an array otherwise
 //format will try to interpolate the properties into the string.
 format("%j", [{a : "b"}])
     => '{"a":"b"}'
 format("%1j, %4j", [{a : "b"}, {a : "b"}])
     => '{\n "a": "b"\n},\n{\n    "a": "b"\n}'
 format("{hello}, {world}", {hello : "Hello", world : "World")
     => "Hello, World";
 format({[-s10]apple}, {[%#10]orange}, {[10]banana} and {[-10]watermelons}",
                     {
                         apple : "apple",
                         orange : "orange",
                         banana : "bananas",
                         watermelons : "watermelons"
       });
     => applesssss, ####orange,    bananas and watermelon
Parameters:
{String} str
the string to format, if you want to use a spacing character as padding (other than \\s) then put your format in brackets.
  1. String Formats %[options]s
    • - : left justified
    • Char : padding character Excludes d,j,s
    • Number : width
  2. Number Formats %[options]d
    • - : left justified
    • + : signed number
    • Char : padding character Excludes d,j,s
    • Number : width
  3. Object Formats %[options]j
    • Number : spacing for object properties.
{Object|Array|Arguments...} obj
the parameters to replace in the string if an array is passed then the array is used sequentially if an object is passed then the object keys are used if a variable number of args are passed then they are used like an array
Returns:
{String} the formatted string
!date && (date = require("./date"));
if (obj instanceof Array) {
    var i = 0, len = obj.length;
    
    return str.replace(FORMAT_REGEX, function(m, format, type) {
        var replacer, ret;
        if (i < len) {
            replacer = obj[i++];
        } else {
            
            
            return m;
        }
        if (m == "%s" || m == "%d" || m == "%D") {
            
            ret = replacer;
        }else if(m == "%Z"){
            ret = replacer.toUTCString();
        } else if (m == "%j") {
            try {
                ret = JSON.stringify(replacer);
            } catch(e) {
                throw new Error("comb.string.format : Unable to parse json from ", replacer);
            }
        } else {
            format = format.replace(/^\[|\]$/g, "");
            switch (type) {
                case "s":
                    ret = formatString(replacer, format);
                    break;
                case "d":
                    ret = formatNumber(replacer, format);
                    break;
                case "j":
                    ret = formatObject(replacer, format);
                    break;
                case "D":
                    ret = date.date.format(replacer, format);
                    break;
                case "Z":
                    ret = date.date.format(replacer, format, true);
                    break;
            }
        }
        return ret;
    });
} else if (typeof obj == "object") {
    return str.replace(INTERP_REGEX, function(m, format, value) {
        value = obj[value];
        if (!misc.isUndefined(value)) {
            if (format) {
                if (comb.isString(value)) {
                    return formatString(value, format);
                } else if (typeof value == "number") {
                    return formatNumber(value, format);
                } else if (date.isDate(value)) {
                    return date.date.format(value, format);
                } else if (typeof value == "object") {
                    return formatObject(value, format);
                }
            } else {
                return "" + value;
            }
        }
        return m;
    });
} else {
    var args = Array.prototype.slice.call(arguments).slice(1);
    return exports.string.format(str, args);
}
    
<static> comb.string.multiply(str, times)
Returns a string duplicated n times;

Example 1 :

comb.string.multiply("HELLO", 5) => "HELLOHELLOHELLOHELLOHELLO"
Parameters:
str
times
var ret = [];
if (times) {
    for (var i = 0; i < times; i++) {
        ret.push(str);
    }
}
return ret.join("");
    
<static> {String} comb.string.pad(string, length, ch, end)
Pads a string

Example 1 :

comb.string.pad("STR", 5, " ", true) => "STR  "
comb.string.pad("STR", 5, "$") => "$$STR"
Parameters:
{String} string
the string to pad
{Number} length
the length of the string when padded
{String} ch Optional, Default: " "
character to pad the string with
{Boolean} end Optional, Default: false
if true then the padding is added to the end
Returns:
{String} the padded string
string = "" + string; 
ch = ch || " ";
var strLen = string.length;
while (strLen < length) {
    if (end) {
        string += ch;
    } else {
        string = ch + string;
    }
    strLen++;
}
return string;
    
<static> comb.string.style(str, styles)
Styles a string according to the specified styles.

Example 1 :

//style a string red
comb.string.style('myStr', 'red');
//style a string red and bold
comb.string.style('myStr', ['red', bold]);
Parameters:
{String} str
The string to style.
{String|Array} styles
the style or styles to apply to a string. options include :
  • bold
  • bright
  • italic
  • underline
  • inverse
  • crossedOut
  • blink
  • red
  • green
  • yellow
  • blue
  • magenta
  • cyan
  • white
  • redBackground
  • greenBackground
  • yellowBackground
  • blueBackground
  • magentaBackground
  • cyanBackground
  • whiteBackground
  • grey
  • black
var ret = str;
if (options) {
    if (ret instanceof Array) {
        ret = ret.map(function(s) {
            return comb.string.style(s, options);
        })
    } else if (options instanceof Array) {
        options.forEach(function(option) {
            ret = comb.string.style(ret, option);
        });
    } else if (options in styles) {
        ret = '\x1B[' + styles[options] + 'm' + str + '\x1B[0m';
    }
}
return ret;
    
<static> comb.string.toArray(str, delimeter)
Converts a string to an array

Example 1 :

comb.string.toArray("a|b|c|d", "|") => ["a","b","c","d"]
comb.string.toArray("a", "|") => ["a"]
comb.string.toArray("", "|") => []
Parameters:
{String} str
the string to parse
{String} delimeter
the delimeter to use
var ret = [];
if (testStr) {
    if (testStr.indexOf(delim) > 0) return testStr.replace(/\s+/g, "").split(delim);
    else return [testStr];
}
return ret;
    
<static> {String} comb.string.truncate(string, length, end)
Truncates a string to the specified length.

Example 1 :

//from the beginning
comb.string.truncate("abcdefg", 3) => "abc";
//from the end
comb.string.truncate("abcdefg", 3,true) => "efg"
//omit the length
comb.string.truncate("abcdefg") => "abcdefg"
Parameters:
{String} string
the string to truncate
{Number} length Optional, Default: -1
the max length of the string, if the string is shorter than the length then the string is returned.
{Boolean} end Optional, Default: false
truncate starting at the end of the string
Returns:
{String} the truncated string.
var ret = string;
if (comb.isString(ret)) {
    if (string.length > length) {
        if (end) {
            var l = string.length;
            ret = string.substring(l - length, l);
        } else {
            ret = string.substring(0, length);
        }
    }
} else {
    ret = comb.string.truncate("" + ret, length);
}
return ret;
    

Documentation generated by JsDoc Toolkit 2.4.0 on Tue Jan 31 2012 16:14:12 GMT-0600 (CST)