If you are trying to use JavaScript’s trim()
function on strings in IE8, you will see, that it throws an error like this:
Message: Object doesn't support this property or method ...
This is because this function is not supported in IE8, even this Microsoft documentation page proves it.
However, there are workarounds of course. Either you can define the trim()
function, or you can use jQuery’s trim().
Defining the trim function
To define the trim function on strings, you need to add the following code:
if(typeof String.prototype.trim !== 'function') { String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); } }
This code uses a regular expression to remove the leading and trailing whitespaces from a string. The if condition makes sure that it is only defined if it does not exist in the first place.
Using jQuery’s trim()
The popular jQuery library contains an implementation of the trim function, so you could use that one too. It is used in a bit different way, because it is not a function on String objects, but it expects the string as a parameter, and returns with the trimmed value. Use it like this:
$.trim( $("#myID").val() );