3

Jan

Filed in Code, JavaScript with 1 comments |

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 :)

1 Responses to "trim() in JavaScript"

Subscribe to this topic with RSS or get the Trackback URL
a (Mar 5th):

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

String.prototype.encodeRE = function() {

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

}

Leave A Reply

 Username (*required)

 Email Address (*private)

 Website (*optional)

Note: Comments moderation may be active so there is no need to resubmit your comment.