1 // $Id$ 2 3 /** 4 * Strip whitespace from the beginning and end of a string. 5 * 6 * @returns {String} The trimmed string. 7 */ 8 String.prototype.trim = function () { 9 return this.replace(/^ +/, '').replace(/ +$/, ''); 10 }; 11 12 /** 13 * A utility method for escaping HTML tag characters. 14 * <p>From Ruby on Rails.</p> 15 * 16 * @returns {String} The escaped string. 17 */ 18 String.prototype.htmlEscape = function () { 19 return this.replace(/"/g, '"').replace(/>/g, '>').replace(/</g, '<').replace(/&/g, '&'); 20 }; 21 22 /** 23 * Escapes the string without affecting existing escaped entities. 24 * <p>From Ruby on Rails.</p> 25 * 26 * @returns {String} The escaped string 27 */ 28 String.prototype.escapeOnce = function () { 29 return this.replace(/"/g, '"').replace(/>/g, '>').replace(/</g, '<').replace(/&(?!([a-zA-Z]+|#\d+);)/g, '&'); 30 }; 31 32 /** 33 * <p>From Ruby on Rails.</p> 34 * 35 * @see http://www.w3.org/TR/html4/types.html#type-name 36 */ 37 String.prototype.sanitizeToId = function () { 38 return this.replace(/\]/g, '').replace(/[^-a-zA-Z0-9:.]/g, '_'); 39 }; 40 41 /** 42 * Does the string end with the specified <tt>suffix</tt>? 43 * <p>From Ruby on Rails.</p> 44 * 45 * @param {String} suffix The specified suffix. 46 * @returns {Boolean} 47 */ 48 String.prototype.endsWith = function (suffix) { 49 return this.substring(this.length - suffix.length) == suffix; 50 }; 51 52 /** 53 * Does the string start with the specified <tt>prefix</tt>? 54 * <p>From Ruby on Rails.</p> 55 * 56 * @param {String} prefix The speficied prefix. 57 * @returns {Boolean} 58 */ 59 String.prototype.startsWith = function (prefix) { 60 return this.substring(0, prefix.length) == prefix; 61 }; 62 63 /** 64 * Equivalent to PHP's two-argument version of strtr. 65 * 66 * @see http://php.net/manual/en/function.strtr.php 67 * @param {Object} replacePairs An associative array in the form: {'from': 'to'} 68 * @returns {String} A translated copy of the string. 69 */ 70 String.prototype.strtr = function (replacePairs) { 71 var str = this; 72 for (var from in replacePairs) { 73 str = str.replace(new RegExp(from, 'g'), replacePairs[from]); 74 } 75 return str; 76 }; 77