3

Jan

Filed in Code, JavaScript |

So today I went searching for a trim() method in JavaScript. Much to my suprise, one didn’t exist. We actually had one locally that another developer had written, but it was only trimming whitespace (no optional argument to trim a certain character). So today, I went ahead and wrote one.

Update: I adjusted the methods to be standalone as well as string prototypes and added some constants from the base trim method.

JavaScript trim(), rtrim(), and ltrim() functions.

function encodeRE(s) { return s.replace(/([.*+?^${}()|[\]\/\\])/g, '\\$1') }
TRIM_BOTH = 0;
TRIM_LEFT = 1;
TRIM_RIGHT = 2;
function trim(v, c, t)
{
    if (!t) var t = TRIM_BOTH;
    if (!c) var c = '\\s';
    else c = encodeRE(c);
    var re;
    if (t == TRIM_BOTH) re = new RegExp('^' + c + '+|' + c + '+$', 'g');
    else if (t == TRIM_LEFT) re = new RegExp('^' + c + '+');
    else if (t == TRIM_RIGHT) re = new RegExp(c + '+$');
    return v.replace(re, '');
}
String.prototype.trim = function(c) { return trim(this, c, TRIM_BOTH); };
String.prototype.ltrim = function(c) { return trim(this, c, TRIM_LEFT); };
String.prototype.rtrim = function(c) { return trim(this, c, TRIM_RIGHT); };

Thanks to Theodore Zoulias for the encodeRE method :)

  • a

    In String.prototype fashion, encodeRE looks better like this:

    String.prototype.encodeRE = function() {

    return this.replace(/([.*+?^${}()|[\]\/\\])/g, ‘\\$1′);

    }

  • http://www.whadiz.com John
  • http://www.air-jordan-10.com/ air jordan 10

    Well , the view of the passage is totally correct ,your details is really reasonable and you guy give us valuable informative post, I totally agree the standpoint of upstairs. I often surfing on this forum when I m free and I find there are so much good information we can learn in this forum! http://spoon8.net/

blog comments powered by Disqus