44

JavaScript doesn't seem to have a native trim() method. How can I trim white spaces at the start and end of a string with JavaScript?

TylerH
  • 20,799
  • 66
  • 75
  • 101
MDCore
  • 17,583
  • 8
  • 43
  • 48

19 Answers19

42

The shortest form for jQuery:

string = $.trim(string);

Link

Darryl Hein
  • 142,451
  • 95
  • 218
  • 261
32

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
  • 36,282
  • 18
  • 72
  • 87
  • According to the linked page the only difference between \s+ and \s\s* is that the latter is a little bit faster. – Pat Oct 30 '08 at 09:45
  • 1
    If you read further, the modified trim11 mentioned at the end of the article is a better method for longer strings. – Chris MacDonald Oct 30 '08 at 11:48
  • 2
    This is an old thread and meanwhile native trim is implemented in Javascript. Pat's regular expression and also Chris MacDonald mentioned trim11 are extremely slow and also jquery's trim is slow in some browsers ( http://jsperf.com/mega-trim-test/16 ). Much faster trim implementation is here: http://stackoverflow.com/a/12547889/1691517 . – Timo Kähkönen Sep 29 '12 at 11:05
27

I know this question is ancient but now, Javascript actually does have a native .trim()

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim

MDCore
  • 17,583
  • 8
  • 43
  • 48
K. R.
  • 1,220
  • 17
  • 20
  • 2
    You're right! Native is always better. It's only from IE9 and up, but in a few years that won't matter much either. – MDCore May 18 '14 at 15:51
  • @MDCore thanks for accepting my answer and mentioning the minimum IE version. But what are you referring to when you say it won't matter in a few years, are you saying javascript will become obsolete? – K. R. May 19 '14 at 16:52
  • 2
    @KR So I asked this question five and a half years ago. Since then trim() has become a standard function. I considered merely pointing out that we're *almost* there in terms of IE support, but in another five and a half years that will be moot. I'd rather people used the native functions and use one of the many other answers if they're stuck with IE8. – MDCore May 19 '14 at 21:34
18

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.
John Topley
  • 113,588
  • 46
  • 195
  • 237
gizmo
  • 11,819
  • 6
  • 44
  • 61
8

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
  • 12,506
  • 6
  • 36
  • 37
7

A slightly tinier version of @Pat's.

return str.replace( /^\s+|\s+$/g, '' );
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
harpo
  • 41,820
  • 13
  • 96
  • 131
6

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
  • 854,327
  • 234
  • 1,573
  • 1,953
5

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
  • 176,118
  • 18
  • 189
  • 202
5

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
  • 5,298
  • 1
  • 24
  • 25
4

I made a trim-function speed in mind. This function beats in a clear difference all of 24 competitors (of which many use regular expressions) and also native string.trim() of Chrome and Chromium(!) and performs as speedy as Safari's trim(). Test results are here: http://jsperf.com/mega-trim-test/7

function trim27(str) {
  var c;
  for (var i = 0; i < str.length; i++) {
    c = str.charCodeAt(i);
    if (c == 32 || c == 10 || c == 13 || c == 9 || c == 12)
    continue; else break;
  }
  for (var j = str.length - 1; j >= i; j--) {
    c = str.charCodeAt(j);
    if (c == 32 || c == 10 || c == 13 || c == 9 || c == 12)
    continue; else break;
  }
  return str.substring(i, j + 1);
}

The function trims characters " \n\r\t\f", but it's easy to add more whitespace-characters, eg. those that regexp uses as whitespaces (\s) with only a minor performance lost ( please see http://jsperf.com/mega-trim-test/8 ).

Edit: The previous trim27() trims only the most common characters (" \n\r\t\f"), but to trim all possible whitespaces, I included below a new function mytrim():

if (!String.prototype.trim || "\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF".trim() || navigator.userAgent.toString().toLowerCase().indexOf("chrome") != -1)
    var mytrim = function(str) {
        var c;
        for (var i = 0; i < str.length; i++) {
            c = str.charCodeAt(i);
            if (c == 32 || c == 10 || c == 13 || c == 9 || c == 12 || c == 11 || c == 160 || c == 5760 || c == 6158 || c == 8192 || c == 8193 || c == 8194 || c == 8195 || c == 8196 || c == 8197 || c == 8198 || c == 8199 || c == 8200 || c == 8201 || c == 8202 || c == 8232 || c == 8233 || c == 8239 || c == 8287 || c == 12288 || c == 65279)
            continue; else break;
        }
        for (var j = str.length - 1; j >= i; j--) {
            c = str.charCodeAt(j);
            if (c == 32 || c == 10 || c == 13 || c == 9 || c == 12 || c == 11 || c == 160 || c == 5760 || c == 6158 || c == 8192 || c == 8193 || c == 8194 || c == 8195 || c == 8196 || c == 8197 || c == 8198 || c == 8199 || c == 8200 || c == 8201 || c == 8202 || c == 8232 || c == 8233 || c == 8239 || c == 8287 || c == 12288 || c == 65279)
            continue; else break;
        }
        return str.substring(i, j + 1);
    };
    else var mytrim = function(str) {
        return str.trim();
    }

Use it this way:

var foo = mytrim(" \n \t Trimmed \f \n "); // foo is now "Trimmed"

The above mytrim() does the following:

  • Trims 26 different whitespaces (all of 25 whitespaces mentioned in http://perfectionkills.com/whitespace-deviations/ and additionally uFEFF, which is ZERO WIDTH NO-BREAK SPACE.
  • Makes trimming results consistent across browsers.
  • Uses native trim() if it is available AND has ability to trim all of 27 different whitespaces. The exception is Chrome and Chromium which both have so slow native trim() that instead of native we use our custom trim.
  • AND THE MOST IMPORTANT: Is not beautiful and is not short, but IS CLEARLY FASTER than any of the 24 competitive alternatives in http://jsperf.com/mega-trim-test/12 (exception: rather old Firefox 3.6.25 in Windows 7 runs mytrim() rather slowly for unknown reason).
Timo Kähkönen
  • 11,962
  • 9
  • 71
  • 112
3

I use this with native JavaScript

// Adding trim function to String object if its not there
if(typeof String.prototype.trim !== 'function') {
  String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, '');
  }
}

Use like this

var myString = "                  some text                  ";

alert(myString.trim());

Example

// Adding trim function to String object if its not there
if(typeof String.prototype.trim !== 'function') {
  String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, '');
  }
}

var str = "      some text              ";
console.log(str.trim());
kiranvj
  • 32,342
  • 7
  • 71
  • 76
1

I use this.

    String.prototype.trim = function() {
        return this.replace(/^\s+|\s+$/g,"");
    }
jamesmhaley
  • 44,484
  • 11
  • 36
  • 49
1

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
  • 110,170
  • 32
  • 120
  • 176
1

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
  • 33,874
  • 33
  • 95
  • 118
0

This is probably not the fastest, and might violate what ".trim()" probably should really be, but I don't like RegExs (mainly because it takes so much time to figure out what they really mean/do) and I like having something that I know will work regardless of whether I have jQuery or not (not to mention the right version, since I tried $.trim(myVar) with jQuery 1.4.2 and it does not work), and will get rid of ALL extra spaces, not just at the end, rebuilding it like it should be:

function Trim(obj) {
    var coll = "";
    var arrObj = obj.split(' ');

    for (var i=0;i<arrObj.length;i++) {
        if (arrObj[i] == "") {
            arrObj.splice(i,1);  // removes array indices containing spaces
        }
    }
    //alert(arrObj.length);  // should be equal to the number of words
    // Rebuilds with spaces in-between words, but without spaces at the end
    for (var i=0;i<arrObj.length;i++) {
        if (arrObj[i] != "" && i != arrObj.length-1)
            coll += arrObj[i] + " ";
        if (arrObj[i] != "" && i == arrObj.length-1)
            coll += arrObj[i];
    }

    return coll;
}
vapcguy
  • 7,097
  • 1
  • 56
  • 52
0

Actually, with jQuery this seems to be the way:

jQuery.trim(string)

(Reference)

Evan
  • 18,183
  • 8
  • 41
  • 48
0

This is an old question but none of these worked for me. I just needed to trim leading and trailing white space and this is what I did. My div tag had an id = start-date.

$("#start-date").text().trim()
CodeChops
  • 1,980
  • 1
  • 20
  • 27
  • "*This is an old question but none of these worked for me.*" Really? Not even [the native trim mentioned by K.R.](https://stackoverflow.com/questions/196925/what-is-the-best-way-to-trim-in-javascript/23719137#23719137)? – Franklin Yu Apr 18 '18 at 16:55
0

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
  • 1,283
  • 10
  • 7
0

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;
    }
}
Kaushik
  • 2,072
  • 1
  • 23
  • 31
RaviRaj
  • 1
  • 1
  • 1