.trim() in JavaScript not working in IE

.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

Solutions/Answers:

Solution 1:

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

Solution 2:

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/).

Solution 3:

jQuery:

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

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

Solution 4:

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

Solution 5:

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.

Solution 6:

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