466

I tried to apply .trim() to a string in one of my JavaScript programs. It's working fine under Mozilla, but an error displays when I try it in IE8. Does anyone know what is going on here? Is there anyway I can make it work in IE?

code:

var ID = document.getElementByID('rep_id').value.trim();

error display:

Message: Object doesn't support this property or method
Line: 604
Char: 2
Code: 0
URI: http://test.localhost/test.js
Shog9
  • 146,212
  • 34
  • 221
  • 231
Jin Yong
  • 38,582
  • 71
  • 132
  • 177
  • 2
    I can't see what is stored on your computer. Could you upload test.js to a storage website? Also, I need to see the actual trim() function to see what is wrong. Thanks! – Warty Feb 22 '10 at 00:38
  • 6
    @ItzWarty `"whatever ".trim()` try that on IE8. – Dan Rosenstark Feb 22 '10 at 01:08
  • 3
    FYI: http://msdn.microsoft.com/en-us/library/ie/ff679971(v=vs.94).aspx – Grim Jan 22 '13 at 08:51
  • 8
    I Googled for IE8 compatibility for `trim()`, and wouldn't believe my eyes when I figured out it was unsupported. Thanks for clearing that out. I was going to ask the same as you asked. – Mathias Lykkegaard Lorenzen Feb 06 '13 at 14:46

14 Answers14

777

Add the following code to add trim functionality to the string.

if(typeof String.prototype.trim !== 'function') {
  String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, ''); 
  }
}
Ben Rowe
  • 26,794
  • 6
  • 50
  • 72
  • 8
    Good answer. Note that `replace(/^\s\s*/, '').replace(/\s\s*$/, '')` should be about 3 times faster than `replace(/^\s+|\s+$/, '')` in Firefox 2, according to one benchmark: http://blog.stevenlevithan.com/archives/faster-trim-javascript – Daniel Vassallo Feb 22 '10 at 00:53
  • 92
    Note also that `replace(/^\s+|\s+$/, '')` only removes either leading or trailing spaces, which is not the behavior expected from a trim function. If you want to remove both leading and trailing spaces you need to use `replace(/^\s+|\s+$/g, '')`. – Massimiliano Fliri Apr 29 '10 at 15:13
  • 1
    Seems a bit silly to me. Doesn't every js framework provide a utility trim() function? If this is the only issue you have, then fine, but there's plenty of ways that IE is "different" that will make a library worth-while in the short-run. – Stephen Feb 02 '11 at 23:43
  • 6
    @Stephen Yes you're correct, but the question isn't about frameworks. it's about javascript & trim. – Ben Rowe Feb 04 '11 at 00:41
  • 1
    You'll find true speed performance of `trim` methods on [Ultimate Comparison of Trim Methods](http://jsperf.com/comparison-of-trim-methods). – Ryan Apr 06 '11 at 19:54
  • 1
    @Stephen also, we use Ext and version 3.x had `trim` but they broke it in `IE` with version 4.x. So we had to use our own. – cbmeeks Aug 12 '11 at 14:27
  • 1
    Just stumbled upon this. Missing trim() is by far the most surprising IE shortcoming I've heard of until now. – Armatus Aug 28 '12 at 13:46
  • Another trim benchmark with more advanced / non-regex methods also included: http://jsperf.com/mega-trim-test/25 – jacobq Jan 24 '13 at 17:15
  • @Daniel Vassallo My test on FireFox 20 shows these times: .trim();//43ms/10000 , .replace(/^\s+|\s+$/g, '');//55ms/10000 , .replace(/^\s\s*|\s\s*$/g, '');//50ms/10000 , .replace(/^\s\s*/, '').replace(/\s\s*$/, '');//62ms/10000 – MrHIDEn Jun 10 '13 at 21:38
  • 3
    This is a nice solution if you don't use jQuery. But if not, $.trim() seems to be a much better solution, as it keeps your script a little bit simpler. – NLemay Dec 13 '13 at 19:31
203

It looks like that function isn't implemented in IE. If you're using jQuery, you could use $.trim() instead (http://api.jquery.com/jQuery.trim/).

jrummell
  • 41,300
  • 17
  • 110
  • 165
  • 17
    Now, I love jQuery, but importing it just for .trim() seems overkill – Erik Feb 22 '10 at 00:58
  • 71
    I agree. That's why I said "if you're using jQuery ..." =) – jrummell Feb 22 '10 at 01:00
  • @Erik is this going to be the only IE issue Jin is going to run into? There's not a lot of useful javascript I can write without having to use a library's browser sanitisation functions. – Stephen Feb 02 '11 at 23:19
  • 8
    Please note that $.trim() is diff from $(.val().trim() - more info here: http://stackoverflow.com/questions/4315570/why-does-internet-explorer-not-like-this-jquery – sami Jun 28 '11 at 08:46
57

jQuery:

$.trim( $("#mycomment").val() );

Someone uses $("#mycomment").val().trim(); but this will not work on IE.

Sampson
  • 251,934
  • 70
  • 517
  • 549
Dan
  • 930
  • 8
  • 13
34

Unfortunately there is not cross browser JavaScript support for trim().

If you aren't using jQuery (which has a .trim() method) you can use the following methods to add trim support to strings:

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+$/,"");
}
Iain Collins
  • 6,139
  • 2
  • 40
  • 38
12

https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Global_Objects/String/Trim

This is a pretty recent addition to javascript, and its not supported by IE.

Erik
  • 19,600
  • 7
  • 43
  • 75
8

I had a similar issue when trying to trim a value from an input and then ask if it was equal to nothing:

if ($(this).val().trim() == "")

However this threw a spanner in the works for IE6 - 8. Annoyingly enough I'd tried to var it up like so:

   var originalValue = $(this).val();

However, using jQuery's trim method, works perfectly for me in all browsers..

var originalValueTrimmed = $.trim($(this).val());              
            if (originalValueTrimmed  == "") { ... }
kaichanvong
  • 371
  • 3
  • 12
5

I have written some code to implement the trim functionality.

LTRIM (trim left):

function ltrim(s)
{
    var l=0;
    while(l < s.length && s[l] == ' ')
    {   l++; }
    return s.substring(l, s.length);
} 

RTRIM (trim right):

function rtrim(s)
{
    var r=s.length -1;
    while(r > 0 && s[r] == ' ')
    {   r-=1;   }
    return s.substring(0, r+1);
 }

TRIM (trim both sides):

function trim(s)
{
    return rtrim(ltrim(s));
}

OR

Regular expression is also available which we can use.

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

Useful Explanation

Community
  • 1
  • 1
shiv.mymail
  • 1,111
  • 3
  • 15
  • 22
  • 3
    Your old school search and destroy code does not handle `\t`, `\r`, `\n` and such. Only `spaces`. Regexp is better if you don't feel like really putting in the effort to manually handle everything. – CodeAngry Oct 27 '13 at 22:37
4

We can get official code From the internet! Refer this:

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

Running the following code before any other code will create trim() if it's not natively available.

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

for more: I just found there is js project for supporting EcmaScript 5: https://github.com/es-shims/es5-shim by reading the source code, we can get more knowledge about trim.

defineProperties(StringPrototype, {
 // http://blog.stevenlevithan.com/archives/faster-trim-javascript
 // http://perfectionkills.com/whitespace-deviations/
  trim: function trim() {
    if (typeof this === 'undefined' || this === null) {
      throw new TypeError("can't convert " + this + ' to object');
    }
    return String(this).replace(trimBeginRegexp, '').replace(trimEndRegexp, '');
  }
}, hasTrimWhitespaceBug);
Will V King
  • 131
  • 1
  • 3
3

I had the same problem in IE9 However when I declared the supported html version with the following tag on the first line before the

<!DOCTYPE html>
<HTML>
<HEAD>...
.
.

The problem was resolved.

Mark
  • 150
  • 1
  • 12
3

I don't think there's a native trim() method in the JavaScript standard. Maybe Mozilla supplies one, but if you want one in IE, you'll need to write it yourself. There are a few versions on this page.

Sampson
  • 251,934
  • 70
  • 517
  • 549
JW.
  • 47,690
  • 30
  • 108
  • 133
1

This is because of typo error getElementByID. Change it to getElementById

Jobelle
  • 2,347
  • 1
  • 13
  • 21
0
var res = function(str){
    var ob; var oe;
    for(var i = 0; i < str.length; i++){
        if(str.charAt(i) != " " && ob == undefined){ob = i;}
        if(str.charAt(i) != " "){oe = i;}
    }
    return str.substring(ob,oe+1);
}
Stephen P
  • 13,259
  • 2
  • 40
  • 61
Dhaval dave
  • 172
  • 2
  • 9
  • 1
    Why do a loop when you can use a simple replace, also its very bad when time is crutial, try calling this method 200 times on average size text and calling the other implementation provided by jQuery and you'll see what i am talking about :) – Dany Khalife Nov 10 '11 at 00:29
  • 1
    Because in some cases a loop is faster than a regexp. See the link that JW posted in his answer for some benchmarks, especially the comments there (since the original benchmark is quite old). – Eric Dec 02 '11 at 21:21
0

This issue can be caused by IE using compatibility mode on intranet sites. There are two ways to resolve this, you can either update IE to not use compatibility mode on your local machine (in IE11: Tools-> Compatibility View Settings -> Uncheck Display intranet sites in Compatibility View)

Better yet you can update the meta tags in your webpage. Add in:

...
<head>
   <meta http-equiv="X-UA-Compatible" content="IE=edge">
</head>
...

What does this mean? It is telling IE to use the latest compatibility mode. More information is available in MSDN: Specifying legacy document modes

FuzzyJulz
  • 2,334
  • 1
  • 13
  • 18
0

Just found out that IE stops supporting trim(), probably after a recent windows update. If you use dojo, you can use dojo.string.trim(), it works cross platform.

Sampson
  • 251,934
  • 70
  • 517
  • 549
David Zhao
  • 3,726
  • 11
  • 42
  • 58