Jin Yong
Jin Yong

Reputation: 43788

.trim() in JavaScript not working in IE

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

Upvotes: 469

Views: 233786

Answers (14)

jrummell
jrummell

Reputation: 43097

It looks like that function isn't implemented in IE. If you're using jQuery, you could use $.trim() instead (although is has been deprecated as of jQuery 3.5).

Upvotes: 202

Kai Vong
Kai Vong

Reputation: 381

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  == "") { ... }

Upvotes: 8

Jobelle
Jobelle

Reputation: 2834

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

Upvotes: 1

FuzzyJulz
FuzzyJulz

Reputation: 2874

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

Upvotes: 0

Will V King
Will V King

Reputation: 131

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);

Upvotes: 4

Iain Collins
Iain Collins

Reputation: 6884

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+$/,"");
}

Upvotes: 33

S.P Singh
S.P Singh

Reputation: 1289

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

Upvotes: 5

Mark
Mark

Reputation: 194

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.

Upvotes: 3

David Zhao
David Zhao

Reputation: 4514

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.

Upvotes: 0

JW.
JW.

Reputation: 51668

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.

Upvotes: 3

Dan
Dan

Reputation: 970

jQuery:

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

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

Upvotes: 57

Dhaval dave
Dhaval dave

Reputation: 172

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

Upvotes: 0

Ben Rowe
Ben Rowe

Reputation: 28721

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

Upvotes: 779

Erik
Erik

Reputation: 20722

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.

Upvotes: 13

Related Questions