Tuesday, June 10, 2014

What happens when we try to use String.trim in IE 8?

Problem: 

var tempString = " my string ";

//in modern browsers
console.log(tempString ); //outputs " my string "
console.log(tempString .trim()); //outputs "my string"

//in IE 8
console.log(tempString.trim()); //error: Object doesn't support property or method\
'trim'

Solution:
We can use a better trim function which works in every browser:

Taken from JQuery.js

// Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE)
var trimPattern = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g
var myTrim = function( text ) {
return text == null ? "" : ( text + "" ).replace( trimPattern, "" );
}
console.log(myTrim(tempString));

This should work in every browser including IE8 as well.

No comments: