/* libenglish.js * * Functions and routines for easy English-language handling. * Much like a JavaScript reimplementation of my libenglish.php * library. * (c) 2005 by Kagan D. MacTane */ function ucfirst(string) { // Uppercases the first character of the string passed to it. first = string.substr(0,1).toUpperCase(); rest = string.substr(1); return first + rest; } // ------------------------------------------------------------- function english_list(array, nocomma) { // Takes a reference to an array, and returns a string that // lists the array's contents in normal English (using commas // and the word "and" if needed). For example, the array (foo, // bar) becomes "foo and bar"; (foo, bar, wombat) becomes "foo, // bar, and wombat". The optional "nocomma" variable, if true, // suppresses the use of the serial comma (aka the Oxford comma), // providing "foo, bar and wombat". nocomma = (nocomma == null) ? 0 : 1 ; switch (array.length) { case 0: return ''; break; case 1: return array[0]; break; case 2: return (array.join(' and ')); break; default: array.splice(-1, 0, 'and'); string = array.join(', '); if (nocomma) { string = string.replace(/, and, /, ' and '); } else { string = string.replace(/, and, /, ', and '); } return string; } } // ------------------------------------------------------------- function add_commas(amount, delim) { // Takes in a number (or a string that represents a numeric // value), and adds commas every three places. For example, // turns 123456.78 into 123,456.78; or 12345678 into // 12,345,678. The optional "delim" argument can be used to // alter the delimiter away from its default of ','. if(typeof amount != "string" && typeof amount != "number") { return ''; } if (typeof delim != "string") { delim = ","; } // If there's a decimal hanging off this number, save it for later. var cents = amount.toString(); var dollars = cents; if (dollars.indexOf('.') == -1) { cents = ''; } else { cents = cents.substr(cents.indexOf('.') + 1); dollars = dollars.substr(0, dollars.indexOf('.')); } // Also check to see if there's any minus sign. var minus = ''; if (dollars < 0) { minus = '-'; dollars *= -1; } var num = new String(dollars); var arr = new Array(); while (num.length > 3) { var group = num.substr(num.length - 3); arr.unshift(group); num = num.substr(0, num.length - 3); } if (num.length > 0) { arr.unshift(num); } num = arr.join(delim); switch (cents.length) { case 0: amount = num.concat('.00'); break; case 1: amount = num + '.' + cents; amount = amount.concat('0'); break; default: amount = num + '.' + cents; } amount = minus + amount; return amount; }