[javascript] .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

This question is related to javascript internet-explorer trim

The answer is


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.


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


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.


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

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


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

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


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


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

jQuery:

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

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


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.


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.


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

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to internet-explorer

Support for ES6 in Internet Explorer 11 The response content cannot be parsed because the Internet Explorer engine is not available, or Flexbox not working in Internet Explorer 11 IE and Edge fix for object-fit: cover; "Object doesn't support property or method 'find'" in IE How to make promises work in IE11 Angular 2 / 4 / 5 not working in IE11 Text in a flex container doesn't wrap in IE11 How can I detect Internet Explorer (IE) and Microsoft Edge using JavaScript? includes() not working in all browsers

Examples related to trim

How to remove whitespace from a string in typescript? Strip / trim all strings of a dataframe Best way to verify string is empty or null Does swift have a trim method on String? Trim specific character from a string Trim whitespace from a String Remove last specific character in a string c# How to delete specific characters from a string in Ruby? How to Remove the last char of String in C#? How to use a TRIM function in SQL Server