For any serious enterprise web apps, there are a handful of default Javascript functions I like to include in order to make my life easier in the long run.
Today, I present some handy extensions to the String object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | String.prototype.trim = function () { return this.replace(/(^\s+)|(\s+$)/, ''); } String.prototype.addTrailingSlash = function () { return ('/' != this.charAt(this.length - 1)) ? this.toString() + '/' : this.toString(); } String.prototype.left = function (n) { if (n <= 0) return ""; else if (n > String(this).length) return this; else return String(this).substring(0,n); } String.prototype.right = function (n){ if (n <= 0) return ""; else if (n > String(this).length) return str; else { var iLen = String(this).length; return String(this).substring(iLen, iLen - n); } } |
The .trim() method is generally quite useful everywhere where text input is accepted.
The .addTrailingSlash() method is a nice way to help guarantee that you get valid paths and URLs when variables are involved.
The other two methods — .left() and .right() — are merely a conveniece at times, and I actually don’t find myself using them much as I prefer proper use of the .substring() method.
