.trim() in JavaScript not working in IE

JavascriptInternet ExplorerTrim

Javascript Problem Overview


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</pre>

Javascript Solutions


Solution 1 - Javascript

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 - Javascript

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

Solution 3 - Javascript

jQuery:

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

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

Solution 4 - Javascript

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 - Javascript

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 - Javascript

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

Solution 7 - Javascript

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

Solution 8 - Javascript

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

Solution 9 - Javascript

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.

Solution 10 - Javascript

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.

Solution 11 - Javascript

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

Solution 12 - Javascript

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

Solution 13 - Javascript

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.

Solution 14 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJin YongView Question on Stackoverflow
Solution 1 - JavascriptBen RoweView Answer on Stackoverflow
Solution 2 - JavascriptjrummellView Answer on Stackoverflow
Solution 3 - JavascriptDanView Answer on Stackoverflow
Solution 4 - JavascriptIain CollinsView Answer on Stackoverflow
Solution 5 - JavascriptErikView Answer on Stackoverflow
Solution 6 - JavascriptkaichanvongView Answer on Stackoverflow
Solution 7 - Javascriptshiv.mymailView Answer on Stackoverflow
Solution 8 - JavascriptWill V KingView Answer on Stackoverflow
Solution 9 - JavascriptJW.View Answer on Stackoverflow
Solution 10 - JavascriptMarkView Answer on Stackoverflow
Solution 11 - JavascriptJobelleView Answer on Stackoverflow
Solution 12 - JavascriptDhaval daveView Answer on Stackoverflow
Solution 13 - JavascriptDavid ZhaoView Answer on Stackoverflow
Solution 14 - JavascriptFuzzyJulzView Answer on Stackoverflow