Coder Perfect

In JavaScript, how can I trim a string?

Problem

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?

Asked by Vinod

Solution #1

Since Internet Explorer 9+, all browsers support a trim() method for strings:

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

You can use this polyfill from MDN if your browser doesn’t support trim():

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, '');
        };
    })();
}

If you’re using jQuery, you may also use $.trim(str), which handles undefined/null values.

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,' ');};

Answered by Pradeep Kumar Mishra

Solution #2

If you’re already using jQuery, the trim function comes in handy.

$.trim('  your string   ');

Because I frequently use jQuery, cutting strings with it is second nature to me. Is it feasible, though, that there is a reaction against jQuery? 🙂

Answered by barneytron

Solution #3

Although there are several right answers above, it should be noted that as of ECMAScript 5, the String object in JavaScript has a native.trim() method. Any attempt to prototype the trim method should, in theory, first check to see if it already exists.

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

JavaScript 1.8.1 / ECMAScript 5 support has been added natively.

Thus supported in:

Firefox: 3.5+

Safari: 5+

IE9+ is the latest version of Internet Explorer. (Only in Standard mode!) http://blogs.msdn.com/b/ie/archive/2010/06/25/enhanced-scripting-in-ie9-ecmascript-5-support-and-more.aspx

Chrome: 5+

Opera: 10.5+

http://kangax.github.com/es5-compat-table/ ECMAScript 5 Support Table

Answered by scunliffe

Solution #4

There are numerous implementations to choose from. The most obvious appears to be as follows:

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

" foo bar ".trim();  // "foo bar"

Answered by Gumbo

Solution #5

Here’s a simple version. What is a general JavaScript trim function?

function trim(str) {
        return str.replace(/^\s+|\s+$/g,"");
}

Answered by Mark Davidson

Post is based on https://stackoverflow.com/questions/498970/trim-string-in-javascript