views:

3534

answers:

14

The question says it all; JS doesn't seem to have a native trim() method.

+18  A: 

according to this page the best all-around approach is

return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');

Of course if you are using jQuery , it will provide you with an optimized trim method.

Pat
\s\s* is redundant.
eyelidlessness
According to the linked page the only difference between \s+ and \s\s* is that the latter is a little bit faster.
Pat
If you read further, the modified trim11 mentioned at the end of the article is a better method for longer strings.
Chris MacDonald
A: 

The answer to so many JavaScript questions: jQuery

$j.trim(string)



Note: the above assumes your jQuery has been setup with:

<script type="text/javascript">$j = jQuery.noConflict();</script>

Which is far more sensible than "$", and far less verbose than typing "jQuery" every time.

Peter Boughton
The jQuery object. Far more sensible than just using $.<script type="text/javascript" src="jquery.js"></script><script type="text/javascript">$j = jQuery.noConflict();</script>
Peter Boughton
+4  A: 

A slightly tinier version of @Pat's.

return str.replace( /^\s+|\s+$/g, '' );
harpo
I think you need to execute that on the text in your method call. ;)
J c
+6  A: 

For ltrim, replace spaces anchored at the start of the string with nothing:

str2 = str.replace(/^\s+/,'');

For rtrim, replace spaces anchored at the end of the string with nothing:

str2 = str.replace(/\s+$/,'');

For trim:

str2 = str.replace(/^\s+|\s+$/g,'');

These all use regex'es to do the actual work.

paxdiablo
+7  A: 

As a couple of others have already noted, it's usually best to do this sort of thing by using a third-party JS library. Not that trim() is a complicated function to build yourself, but there are so many functions that aren't native to JavaScript that you might need and end-up writing yourself, it soon becomes more cost-effective to use a library.

Of course, another advantage of using a JS library is that the authors do the hard work of ensuring that the functions work across all the major browsers, so that you can code to a standard interface and forget about the irritating differences between Internet Explorer and all the other browsers.

Richard Turner
A: 

Actually, with jQuery this seems to be the way:

jQuery.trim(string)

(Reference)

Evan
+9  A: 

The shortest form for jQuery:

string = $.trim(string);

Link

Darryl Hein
+10  A: 

Well, as a lot of people always says, the trim function works pretty well, but if you don't want to use a whole framework just to perform a trim, it may be useful to take a look at its implementation. So here it is:

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

The main advantages I see in this implementation, comparing to other solution already proposed here are:

  • The 'g' flag that allows you to perfom a trim on a multi-line string
  • The (text || "") syntax that ensure that the function will always work, even if the argument passed is null or undefined.
gizmo
best answer here
Chris MacDonald
+1  A: 

Microsoft .NET also has String.trim function as a part of JavaScript Base Type Extensions. It could be used if you are coding ASP.NET application.

Alexander Prokofyev
+3  A: 

Why not just modify the String prototype? Why not steal the trim function from an open source library, like I did here with YUI? (Do you really need to load and entire framework for this simple taks?) Put them together and you get this:

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

var s = " hello ";
alert(s.trim() == "hello"); // displays true
Benry
A: 

I use this.

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

Use Ariel Flesler's fast trim function:

// Licensed under BSD
function myBestTrim( str ){
 var start = -1,
  end = str.length;
 while( str.charCodeAt(--end) < 33 );
 while( str.charCodeAt(++start) < 33 );
 return str.slice( start, end + 1 );
};

My solution, though, would be this (because the String object in Firefox 3.5 and above already has a trim method):

String.prototype.trim = String.prototype.trim || function () {
    var start = -1,
        end   = this.length;

    while( this.charCodeAt(--end) < 33 );
    while( this.charCodeAt(++start) < 33 );

    return this.slice( start, end + 1 );
};
Ionuț G. Stan
A: 

I use this:

Work with functions.

 function trim($) { 
                return (typeof $ == "function" ? $() : $).replace(/[\s]*/g,"")
        }

        code example: 

        trim((function(){ return "a  b"})) // ab

        trim(" a  b") //ab
Jet
A: 

You can use following ...

function trim(str) {
try{
    if(str && typeof(str) == 'string'){
        return str.replace(/^\s*|\s*$/g,"");
    } else {
        return '';
    }
} catch(e) { return str;  } 
RaviRaj