Trim string in JavaScript?

Vinod picture Vinod · Jan 31, 2009 · Viewed 853.4k times · Source

How do I trim a string in JavaScript? That is, how do I remove all whitespace from the beginning and the end of the string in JavaScript?

Answer

Pradeep Kumar Mishra picture Pradeep Kumar Mishra · Jan 31, 2009

All browsers since IE9+ have trim() method for strings:

" \n test \n ".trim(); // returns "test" here

For those browsers who does not support trim(), you can use this polyfill from MDN:

if (!String.prototype.trim) {
    (function() {
        // Make sure we trim BOM and NBSP
        var rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;
        String.prototype.trim = function() {
            return this.replace(rtrim, '');
        };
    })();
}

That said, if using jQuery, $.trim(str) is also available and handles undefined/null.


See this:

String.prototype.trim=function(){return this.replace(/^\s+|\s+$/g, '');};

String.prototype.ltrim=function(){return this.replace(/^\s+/,'');};

String.prototype.rtrim=function(){return this.replace(/\s+$/,'');};

String.prototype.fulltrim=function(){return this.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g,'').replace(/\s+/g,' ');};