Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.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
like image 923
Jin Yong Avatar asked Feb 22 '10 00:02

Jin Yong


People also ask

What is trim () JavaScript?

trim() The trim() method removes whitespace from both ends of a string and returns a new string, without modifying the original string. Whitespace in this context is all the whitespace characters (space, tab, no-break space, etc.)

Is trim deprecated?

trim() is deprecated.

How do you trim a character in JavaScript?

JavaScript provides three functions for performing various types of string trimming. The first, trimLeft() , strips characters from the beginning of the string. The second, trimRight() , removes characters from the end of the string. The final function, trim() , removes characters from both ends.

Can we trim number in JavaScript?

In JavaScript, trunc() is a function that is used to return the integer portion of a number. It truncates the number and removes all fractional digits. Because the trunc() function is a static function of the Math object, it must be invoked through the placeholder object called Math.


2 Answers

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, '');    } } 
like image 136
Ben Rowe Avatar answered Sep 30 '22 21:09

Ben Rowe


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

like image 28
jrummell Avatar answered Sep 30 '22 21:09

jrummell