Williammer
7/9/2014 - 10:42 AM

jsPerform.StrTrim.js - the efficient methods to trim string with and without regular expression.

jsPerform.StrTrim.js - the efficient methods to trim string with and without regular expression.

// trim with regular expression
String.prototype.trim = function () {
    return this.replace(/^\s*([\s\S]*\S)?\s*$/, "$1");
};

// trim with string methods
String.prototype.trim = function () {
    var start = 0,
        end = this.length - 1,
        ws = " \n\r\t\f\x0b\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u202f\u205f\u3000\ufeff";
    while (ws.indexOf(this.charAt(start)) > -1) {
        start++;
    }
    while (end > start && ws.indexOf(this.charAt(end)) > -1) {
        end--;
    }
    return this.slice(start, end + 1);
};

// hybrid solution, both elegant and efficient.
String.prototype.trim = function () {
    var str = this.replace(/^\s+/, ""),
        end = str.length - 1,
        ws = /\s/;
    while (ws.test(str.charAt(end))) {
        end--;
    }
    return str.slice(0, end + 1);
};