JavaScript Alternative trim() function for Internet Explorer

To remove white spaces before or after a string, we use JavaScript trim() function. This JavaScript function is equivalent to PHP trim() function. In JavaScript it is actually a method of string object. The trim() method removes whitespace from both sides of a string.

newString=oldString.trim()

This method is supported in all major browsers Firefox, Chrome, Opera, Safari and latest version of Internet Explorer. But this trim()method is not supported in Internet Explorer 8 and earlier versions.
If you use this method IE8 says: Object doesn’t support this property or method
I am using following alternative custom trim() function for IE.

Alternative Codes:

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

Here I use same prototype name trim. You don’t have to detect the browser name to use this code. No problem, it will not conflict. This code declares trim method if browser does not have this declared previously. Just add above codes to your project. I discovered this codes when I saw my plugin WP Ad Guru did not work in IE 8. I am using this code and my plugin is working fine in IE now. Let me know if this works for you.

Leave a Reply

Your email address will not be published. Required fields are marked *

 

This site uses Akismet to reduce spam. Learn how your comment data is processed.