00 Votes

JavaScript: Internet Explorer 8 and the trim() function

Question by Guest | 2014-05-21 at 10:44

In order to free a string from the white space (spaces and so on) at its beginning and its end, I am usually using the function trim(). Up to now, this has worked in all programming languages and browsers like a charm. However, only up to the date, I ran across the Internet Explorer.

Concretely, it is about the IE8 which gives me the error message "Object doesn't support this property or method" whenever trying to call the trim() function.

Normally, I am only using the Firefox and Chrome browser, so I have not yet noticed this behavior until one of my customers reported it.

Obviously, the Internet Explorer is not supporting the trim() function at all. Is there any workaround known?

ReplyPositiveNegativeDateVotes
0Best Answer0 Votes

In fact, trim() is only supported since IE9 and even in this version, the support is not given in each mode.

One workaround is to just define your own trim function:

if (typeof String.prototype.trim !== 'function') {
  String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, ''); 
  };
}

This function checks in the if-statement whether there is a function "trim" defined or available for the string type. If not, an own function "trim" will be defined consisting of a regular expression. This RegEx cares about removing the white space from both sides of the string.
2014-05-21 at 16:49

ReplyPositive Negative
00 Votes

If you are already using jQuery on your website, you can also just use the trim() function from jQuery:

var s = ' abc ';

s = $.trim(s);

alert(s);  // 'abc'

As you can see in the example, you can simply use this function via $.trim().
2014-05-22 at 17:12

ReplyPositive Negative
Reply

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.